即使我很确定我的问题可能没有解决方案,我仍然想尝试一下,并向大家寻求一些建议。
假设我有一个简单的课程,例如
public class MyIntContainer
{
public int myIntValue;
public bool randomOtherValue;
public MyIntContainer(int value)
{
myIntValue = value;
}
}
现在我要像这样简单地分配变量:
MyIntContainer container = 10;
所以最简单的方法是像这样向我的类添加一个隐式转换运算符
public static implicit operator MyIntContainer(int value)
{
return new MyIntContainer(value);
}
问题是:我想保留randomOtherValue,如果有的话。所以,如果我做这样的事情:
MyIntContainer container = new MyIntContainer(10);
container.randomOtherValue = true;
container = 20;
我希望最新的容器变量的myIntValue = 20并且randomOtherValue = true;我似乎找不到任何方法可以做到这一点。如果只有我们可以以任何方式重载赋值运算符,则可能会发生这种情况。我什至考虑为隐式运算符方法提供一个额外的“此MyIntContainer容器”参数,该参数可以引用赋值运算符之前声明的变量。但显然,这些都不起作用。有没有很好的技巧可以模仿这种行为?
谢谢,谢谢BOTHLine
对于赋值运算符,将值与旧值组合起来没有意义,这不是该符号的含义。
但是,您可能会重载|
(逻辑或),这可以说是值的组合(例如0x10 | 0x01
= 0x11
)。
public class MyIntContainer
{
public int myIntValue;
public bool randomOtherValue;
public MyIntContainer(int value)
{
myIntValue = value;
}
static public MyIntContainer operator | (MyIntContainer lhs, int rhs)
{
return new MyIntContainer(rhs) { randomOtherValue = lhs.randomOtherValue };
}
}
测试:
var x = new MyIntContainer(10);
x.randomOtherValue = true;
x |= 20; //Combine x with the new value of 20
Console.WriteLine("{0} {1}", x.myIntValue, x.randomOtherValue);
输出:
20 true