这个问题专门针对结构。
说我定义:
struct Complex
{
public double real, imaginary;
}
如果我尝试:
var numbers = new[]
{
new Complex() { real = 1, imaginary = 1 },
new Complex() { real = -1, imaginary = -1 }
};
foreach ( var z in numbers )
{
z.real += 1;
}
我得到编译错误:Error: cannot modify members of 'complex' because it is a 'foreach iteration variable'
然而,
var numbers = new List<Complex>();
numbers.Add( new Complex() { real = 1, imaginary = 1 } );
numbers.Add( new Complex() { real = -1, imaginary = -1 } );
numbers.ForEach( z => z.real += 1 );
编译没有错误。牢记“foreach”编译错误,这里有什么理由不给出编译时错误吗?