Accessing a Class property without using dot opera

2019-04-02 06:50发布

问题:

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);
    }
}