c#: 有 class return 没有直接变量引用的值

c#: Have class return value without direct variable reference

我想弄清楚是否可以创建一个 class,默认情况下 returns 是一个没有 method/variable 引用的值。

public class Attribute
{
    public int defaultValue = _base + _mods;

    private int _base;
    private int _mods;

    public Attribute (int b, int m)
    {
        _base = b;
        _mods = m;
    }
}

public class UseAttribute
{
    private Attribute att;

    public Start()
    {
        att = new Attribute(5,2);
    }

    public void CheckAttribute()
    {
        console.WriteLine("att: " + att); //Outputs:"att: 7"
    }
}

这是可以做到的,还是我必须始终使用 att.defaultValue?

有一种方法可以做到这一点,它可以是隐式或显式转换。

public class Attribute
{  
    private int _base;
    private int _mods;

    public Attribute (int b, int m)
    {
        _base = b;
        _mods = m;
    }

    public static implicit operator int(Attribute attr) => attr._base + attr._mods;

    public override string ToString() => $"{this._base + this._mods}";
}

public class UseAttribute
{
    private Attribute att;

    public UseAttribute()
    {
        att = new Attribute(5,2);
    }

    public void CheckAttribute()
    {
        console.WriteLine("att: " + att); //Outputs:"att: 7"
    }
}

最后我不会去争取,更好的方法还是属性。