這是次要的,我知道,但假設我有一個類Character和一個類的能力(主要是因爲這就是我正在做的)。類角色有六種能力(所以典型的D & D ...)。基本上是:如何在C#中爲一個類創建一個簡化的賦值或默認屬性
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 };
}
將替換整個屬性而不是屬性—不想要的結果的僅僅是比分...
作爲該* *真的要做些什麼?沒有名字和縮寫的能力是否有效?你必須記住,你永遠不會真的將這些'int'存儲爲'Ability'能力,因爲它們缺少顯示數據。 –
這是一個很好的觀點,埃德。簡短的回答,並不是真的(特別是因爲名字和Abbr在某個時候弄糟了本地化)。但是,這個例子表明,因爲我需要將「Bonus」,「CurScore」和「CurMod」屬性添加到Ability中。 –
如果你的角色類是靜態的,那很容易。很明顯,你必須有各種角色,所以它不能是靜態的。 – GianT971