在.NET中,当实现隐式转换运算符时,是否可以访问分配给的对象?

时间:2014-04-08 15:25:12

标签: c# casting operators operator-overloading implicit-conversion

例如,如果我有一个对象,例如:

public class MyObject
{
    public MyObject(int initialValue)
    {
        this.InitialValue = initialValue;
        this.CurrentValue = initialValue;
    }

    public int InitialValue { get; set; }

    public int CurrentValue { get; set; }

    public static implicit operator MyObject(int someValue)
    {
        MyObject result = new MyObject(someValue);
        return result;
    }
}

是否有可能在隐式演员表中保留初始值(如果有的话)并且只更新当前值?

这个想法是做这样的事情:

MyObject test = 4; // Both InitialValue and CurrentValue are now 4.
test = 5; // InitialValue is 4 but CurrentValue is now 5.

这是一个很长的镜头,我不认为这是可能的,但如果有任何人有任何出色的想法来实现这一点,我会很感激。

谢谢!

1 个答案:

答案 0 :(得分:-1)

你可以在不做任何转让的情况下进行投射。一个例子是调用函数时:

void SomeFunction(MyObject passedValue) { /* ... */ }

可以通过你的隐式演员来调用:

SomeFunction(5);

并没有任何任务发生。

即使确实发生了分配,请记住您分配给变量,而不是分配给对象。从某种意义上说,在这种情况下,您要求的对象实际上是result变量。