IList <mutable_struct> vs mutable_struct []

Rob*_*ino 7 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;
}
Run Code Online (Sandbox Code Playgroud)

幕后究竟是什么导致编译器阻挠?

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

编译器阻止我修改我想要更改的对象副本的成员.但为什么要从这个阵列制作副本?

更多的研究投入:

var guess = (ValueType[]) bad;
guess[0].Name="Delilah";
Run Code Online (Sandbox Code Playgroud)

现在,您的想法bad[0].Name是什么?没错,这是"Delilah".

das*_*ght 7

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

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

另一方面,当编译器处理接口时,它只知道它返回了您尝试修改的值类型的副本.换句话说,编译器视图IList的运算符[]和数组的运算符[]不同.

注意:不言而喻,这种练习纯粹具有学术价值,因为可变结构是邪恶的.