好的,我们有一些代码:
//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".