【发布时间】:2014-05-21 09:44:47
【问题描述】:
例如,如果我有一个对象,例如:
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.
这是一个长远的目标,我认为这是不可能的,但如果有人有任何出色的想法来实现这一目标,我将不胜感激。
谢谢!
【问题讨论】:
-
否,因为转换运算符总是创建一个 new 对象(它没有对目标对象的任何引用)并且赋值运算符不能被覆盖。您可以做的是牺牲语法以支持
MyObject.Set(ref MyObject target, int value)静态方法(也可以使用扩展方法来完成)。 -
这是一个有趣的想法,但我认为像这样的操作员是不可能的。这可能需要
MyObject类上的方法来更新特定实例的值,并且该方法将保留旧值作为该实例中的状态。 (这个方法确实可以是一个属性的设置器,使其也更加透明。) -
谢谢,我想了很多,但我想无论如何我都会四处打听。
标签: c# casting operators operator-overloading implicit-conversion