gpt4 book ai didi

c# - 如何在 C# 中为类创建简化的赋值或默认属性

转载 作者:太空狗 更新时间:2023-10-29 21:24:13 26 4
gpt4 key购买 nike

我知道这是次要的,但假设我有一个类 Character 和一个类 Ability(主要是因为这就是我正在研究的)。 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 };
}

将替换整个属性而不仅仅是属性的分数——不是期望的结果...

最佳答案

您最多只能通过将这些方法添加到 Ability 来增加分数。

    public static Ability operator + (Ability lhs, int score)
{
lhs.Score += score;
return lhs;
}

public static Ability operator - (Ability lhs, int score)
{
lhs.Score -= score;
return lhs;
}

public static implicit operator int(Ability rhs)
{
return rhs.Score;
}

并像这样使用它们:

    static void Main(string[] args)
{
Character evil = new Character(); //Str.Sccore=10

evil.Str += 10; //cast spell for Str.Sccore=20

evil.Str -= evil.Str; //death with Str.Sccore=0
}

关于c# - 如何在 C# 中为类创建简化的赋值或默认属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7747743/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com