例如,如果我有一个对象,例如:
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.
这是一个很长的镜头,我不认为这是可能的,但如果有任何人有任何出色的想法来实现这一点,我会很感激。
谢谢!
答案 0 :(得分:-1)
你可以在不做任何转让的情况下进行投射。一个例子是调用函数时:
void SomeFunction(MyObject passedValue) { /* ... */ }
可以通过你的隐式演员来调用:
SomeFunction(5);
并没有任何任务发生。
即使确实发生了分配,请记住您分配给变量,而不是分配给对象。从某种意义上说,在这种情况下,您要求的对象实际上是result
变量。