我想设置一个值类型并给它隐式转换。不幸的是,这样做会使其停止表现为参考类型,即
MyTnt i1 = 3; //MyValue has a field value = 3
MyInt i2 = 5; //value = 5
i1 = i2; //both i1 and i2 = 5
i2 = 4; //i1 = 5, i2 = 4; should be i1 = i2 = 4;
是否可以使用隐式转换来编写装箱,以便它在此处按预期运行?
答案 0 :(得分:0)
我相信你误解了一些观点。
有一件事是创建引用来保存对象或值类型,另一件事是给出一个参数by reference。
i1
如果您通过某种方法通过引用传递它,也会保留4
:
public void X(int i2, ref MyInt i1)
{
// When you define a ref parameter
// you're not creating a new reference but you're
// reusing the given one
i1 = i2;
}
MyInt i1 = 4;
MyInt i2 = 0;
// This would produce what you expect
X(i2, ref i1);
// Now i2 is 4