使用装箱和隐式转换使值类型表现得像引用类型

Making value type behave like a reference type using boxing and implicit conversions

我想装箱一个值类型并给它隐式转换。不幸的是,这样做会使它不再像引用类型那样表现,即

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;

是否可以使用隐式转换编写装箱,使其在此处按预期运行?

我相信你误解了一些要点。

一件事是创建 引用 来保存对象或值类型,另一件事是给出参数 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