【问题标题】:c#: Have class return value without direct variable referencec#:没有直接变量引用的类返回值
【发布时间】:2020-01-23 21:38:25
【问题描述】:

我试图弄清楚是否可以创建一个默认返回值而没有方法/变量引用的类。

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 ?

【问题讨论】:

  • 没有类的返回值之类的东西。我想你真正在找什么,如果你想“显示一个对象”是override ToString()
  • 字符串输出只是一个例子。我的主要用例是作为 rpg 角色的属性,它几乎总是只需要返回组合的基础和修饰符值。很遗憾听到这是不可能的,但感谢您的快速回复!

标签: c# return return-value


【解决方案1】:

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

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"
    }
}

最终我不会去追求它并更好地使用方法或属性。

【讨论】:

  • 我不熟悉隐式关键字。看来我要读书了,谢谢!
猜你喜欢
  • 2011-12-09
  • 2012-03-30
  • 1970-01-01
  • 2014-03-13
  • 1970-01-01
  • 1970-01-01
  • 2016-01-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多