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;
}
}
}
对此有什么合理的解释吗?
编译器返回:
错误:
无法修改“ms”的成员,因为它是“foreach 迭代”
多变的'
EDIT:
额外问题:
我刚刚尝试更改字符串MyFunction
,并且它实际上并没有更新ms
。但是:如果我去快速观察并在那里分配相同的值,它会更新ms
。如果一开始就不应该编译,为什么会发生这种情况,quickwatch 不应该抛出异常?
EDIT2:
好吧,快速观看也适用于副本ms
,这就是为什么我可以编辑它的值,它实际上并没有改变内容MyPrivateVariable
.
您将它们用作可变结构。避免这样做:
为什么可变结构是“邪恶的”? https://stackoverflow.com/questions/441309/why-are-mutable-structs-evil
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)