Accessing a Class property without using dot operator

核能气质少年 提交于 2019-12-21 06:26:19

问题


I need to overload some operators when called using Double types. To achieve this, I'm creating a class MyDouble, which inherits from Double. MyDouble looks somewhat like this

class MyDouble : Double
{
   Double value;
   // operator overloads go here
}

I want to abstract away the value property from the user so that it is usable just as a Double. Basically I want the user to be able to do this:

MyDouble a = 5;         //a.value gets assigned 5
Console.WriteLine(a);   //prints a.value

I don't want the user to have to specifically target the value property. Is this possible? How would I go about it?


回答1:


You can define an implicit conversion operator, like this:

class MyDouble {
    public Value {get; private set;}
    public Double(double value) {
        Value = value;
    }
    // Other declarations go here...
    public static implicit operator double(MyDouble md) {
        return md.Value;
    }
    public static implicit operator MyDouble(double d) {
        return new MyDouble(d);
    }
}


来源:https://stackoverflow.com/questions/9494070/accessing-a-class-property-without-using-dot-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!