如何在C#中为类创建简化赋值或默认属性
发布时间:2020-12-15 08:24:45 所属栏目:百科 来源:网络整理
导读:这是次要的,我知道,但是我要说我有一个班级角色和一个班级能力(主要是因为这就是我正在做的事情). Class Character有六种能力(典型的D D ……).基本上: public class Character{ public Character() { this.Str = new Ability("Strength","Str"); this.Dex
这是次要的,我知道,但是我要说我有一个班级角色和一个班级能力(主要是因为这就是我正在做的事情). Class Character有六种能力(典型的D& D ……).基本上:
public class Character { public Character() { this.Str = new Ability("Strength","Str"); this.Dex = new Ability("Dexterity","Dex"); this.Con = new Ability("Constitution","Con"); this.Int = new Ability("Intelligence","Int"); this.Wis = new Ability("Wisdom","Wis"); this.Cha = new Ability("Charisma","Cha"); } #region Abilities public Ability Str { get; set; } public Ability Dex { get; set; } public Ability Con { get; set; } public Ability Int { get; set; } public Ability Wis { get; set; } public Ability Cha { get; set; } #endregion } 和 public class Ability { public Ability() { Score = 10; } public Ability(string Name,string Abbr) : this() { this.Name = Name; this.Abbr = Abbr; } public string Name { get; set; } public string Abbr { get; set; } public int Score { get; set; } public int Mod { get { return (Score - 10) / 2; } } } 在未来的代码中实际使用这些能力属性时,我希望能够默认只得分,如下所示: //Conan hits someone int damage = RollDice("2d6") + Conan.Str; //evil sorcerer attack drains strength Conan.Str = 0; 而不是: //Conan hits someone int damage = RollDie("2d6") + Conan.Str.Score; //evil sorcerer attack drains strength Conan.Str.Score = 0; 现在,第一种情况可以通过隐式转换来处理: public static implicit operator int(Ability a) { return a.Score; } 可以有人帮我反过来吗?这样的隐式转换: public static implicit operator Ability(int a) { return new Ability(){ Score = a }; } 将替换整个属性而不仅仅是属性的分数 – 而不是所需的结果…… 解决方法
首先,保持隐式转换:
public static implicit operator Ability(int a) { return new Ability(){ Score = a }; } 然后在你的角色类中:为str添加一个private属性,并更改Str属性的getter和setter,如下所示: private Ability str; public Ability Str { get { return this.str; } set { if (value.Name == "") { this.str.Score = value.Score; } else { this.str = value; } } } 你去:) 你也可以使用: if(string.IsNullOrWhiteSpace(value.Name)) 代替 if (value.Name == "") 如果您正在编译.NET 4.0版本 编辑:我给了你一个完全符合你想要的解决方案,但是ja72所写的内容对于操作符来说也是一个很好的建议 – 和;你可以将他的解决方案添加到我的(或者我的,无论如何),它会工作得很好.然后你就可以写: Character Jax = new Character(); // Str.Score = 10 Character Conan = new Character(); // Str.Score = 10 Jax.Str = 2000; // Str.Score = 2000; Conan.Str += 150; // Str.Score = 160 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |