這個問題是關於結構的。在IEnumerable foreach vs List中修改結構<T> .ForEach
說我定義:
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'編譯錯誤,是否有任何理由不在這裏給出編譯時錯誤?
他們是同樣危險的事情要嘗試,但一個容易讓編譯器發現,另一個是非常困難的。 – MattW 2013-03-21 17:41:45