简体   繁体   中英

c#: Have class return value without direct variable reference

I'm trying to figure out if it's possible to create a class that returns a value by default without a method/variable reference.

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

Is this something that can be done, or would I have to always use att.defaultValue ?

There is a way how to do this and it would be implicit or explicit conversion.

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

In the end I would not go for it and better use method or property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM