namespace MyNamespace
{
public struct MyStruct
{
public string MyString;
public int MyInt;
public bool MyBool;
}
public class MyClass
{
private List<MyStruct> MyPrivateVariable;
public List<MyStruct> MyVariable
{
get
{
if (MyPrivateVariable == null)
{
MyPrivateVariable = new List<MyStruct>();
MyPrivateVariable.Add(new MyStruct());
MyPrivateVariable.Add(new MyStruct());
}
return MyPrivateVariable;
}
}
public void MyLoop()
{
foreach (MyStruct ms in MyVariable)
{
// Doesn't compile, but it works if you execute it through the Immediate window, or in Quickwatch
ms.MyBool = false;
// Compiles, works
MyFunction(ms);
}
}
public void MyFunction(MyStruct ms)
{
ms.MyBool = false;
}
}
}
對此有何合理的解釋?C中的foreach struct怪異編譯錯誤#
編譯器回報:
Error: Cannot modify members of 'ms' because it is 'foreach iteration variable'
編輯:
額外的問題:
我只是想從MyFunction
改變一個字符串,它實際上並沒有更新ms
。但是:如果我去quickwatch並在那裏分配相同的值,它會更新ms
。爲什麼會發生這種情況,如果它不應該編譯在第一位,不應該quickwatch拋出異常?
EDIT2:
好,見效快的手錶也適用於的ms
副本,所以這就是爲什麼我可以修改它的價值,它實際上並沒有改變的MyPrivateVariable
內容。
什麼是編譯器錯誤? – 2010-09-24 19:18:51
編譯器消息說什麼? – CodingGorilla 2010-09-24 19:19:01
什麼是編譯器錯誤信息? – EJC 2010-09-24 19:19:02