我在 c# 中做了以下示例
interface IChangeable
{
void Change(params Int32[] array);
}
struct SomeValueType : IChangeable
{
private Int32 m_X;
public SomeValueType(int X)
{
m_X = X;
}
public void Change(params Int32[] array)
{
m_X = array[0];
}
public override string ToString()
{
return String.Format("Crt value of m_X: {0}", m_X);
}
}
在主要:
static void Main(String[] args)
{
SomeValueType someValueType = new SomeValueType(5);
Console.WriteLine(someValueType); // No boxing occured. It showed: 5
Object someRefType = someValueType; // Boxed
Console.WriteLine(someRefType); // Also Shows 5 (from heap)
someValueType.Change(2); // Change Value of x not o's
Console.WriteLine(someValueType + " " + someRefType); // 2 5
((SomeValueType)someRefType).Change(3); // Copies to a temp stack so no change ocuured in o
Console.WriteLine(someRefType); // 5
IChangeable itfStackChange = (IChangeable)someValueType;
itfStackChange.Change(7);
Console.WriteLine(someValueType); // Shows 2 and not 7 ... why?
IChangeable itfChange = (IChangeable)someRefType;
itfChange.Change(1); // Unboxes the value of o, making the value of x 1 boxes o again?
Console.WriteLine(someRefType); // Shows 1
}
现在我想知道当我这样做时会发生什么:
IChangeable itfStackChange = (IChangeable)someValueType; //value was 2 and its still 2
itfStackChange.Change(7);
Console.WriteLine(someValueType);
但是,如果我将结构的定义更改为类,例如:
class SomeValueType : IChangeable
它写的是 7 而不是 2。