Accessing a Class property without using dot opera

2019-04-02 06:52发布

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条回答
一纸荒年 Trace。
2楼-- · 2019-04-02 07:30

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);
    }
}
查看更多
登录 后发表回答