IList <mutable_struct> vs mutable_struct [] </mutable_struct>

时间:2014-09-26 13:22:19

标签: c# struct

好的,我们有一些代码:

//I complie nicely
ValueType[] good = new ValueType[1];
good[0].Name = "Robin";

//I don't compile: Cannot modify expression because its not a variable
IList<ValueType> bad = new ValueType[1];
bad[0].Name = "Jerome";

struct ValueType
{
    public string Name;
}

导致编译器阻碍的幕后究竟是怎么回事?

//Adding to watch the following
good.GetType().Name //Value = "ValueType[]" It's a ValueType array.
bad.GetType().Name  //Value = "ValueType[]" Also a ValueType array.

编译器阻止我修改我想要更改的对象副本的成员。但是为什么要从这个数组中制作副本呢?

更多的研究投入:

var guess = (ValueType[]) bad;
guess[0].Name="Delilah";

现在,您认为bad[0].Name是什么?没错,这是“Delilah”。

1 个答案:

答案 0 :(得分:7)

  

为什么值类型是从IList<ValueType>复制返回的,而不是从数组

返回的

因为数组是编译器已知的内置构造。它的运算符[]有一个内置的语义,它为编译器提供了一个可修改的引用。

当编译器处理接口时,另一方面,它只知道它获取了一个值类型的副本,您试图修改它。换句话说,编译器以不同的方式查看IList的运算符[]和数组的运算符[]

注意:不言而喻,这项练习纯粹具有学术价值,因为mutable structs are evil