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

前端之家收集整理的这篇文章主要介绍了如何在C#中为类创建简化赋值或默认属性前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是次要的,我知道,但是我要说我有一个班级角色和一个班级能力(主要是因为这就是我正在做的事情). 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

猜你在找的C#相关文章