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;
}
}
}
对此有什么合理的解释吗?
编译器返回:
Error: Cannot modify members of 'ms' because it is 'foreach iteration variable'
编辑:
补充问题:
我只是尝试更改 MyFunction
中的字符串,但它实际上并没有更新 ms
。但是:如果我转到 quickwatch 并在那里分配相同的值,它会更新 ms
。如果它甚至不应该首先编译,为什么会发生这种情况,quickwatch 不应该抛出异常?
编辑 2:
好的,quick watch 也适用于 ms
的副本,所以这就是我可以编辑它的值的原因,它实际上并没有改变 MyPrivateVariable
的内容。
最佳答案
您将它们用作可变结构。避免这样做:
关于c# - C# 中的 Foreach struct 奇怪的编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3790207/