Foreach结构奇怪的编译错误在C# [英] Foreach struct weird compile error in C#
问题描述
命名空间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(MyVariable中的MyStruct ms)
{
//不编译,但它的工作原理,如果你通过立即窗口或Quickwatch执行它
ms.MyBool = false;
//编译,工作
MyFunction(ms);
}
}
public void MyFunction(MyStruct ms)
{
ms.MyBool = false;
}
}
}
任何合理的解释?
编译器返回:
错误:
无法修改成员'ms',因为它是'foreach迭代
变量'
EDIT: p>
额外的问题:
我刚刚尝试更改 MyFunction
,它实际上不会更新 ms
。但是:如果我去quickwatch并在那里分配相同的值,它会更新 ms
。为什么会发生这种情况,如果它不应该在第一时间编译,不应该quickwatch抛出异常?
EDIT2: / p>
好的,快速观察也适用于 ms
的副本,所以这就是为什么我可以编辑它的值,实际上改变了 MyPrivateVariable
的内容。
使用它们作为可变结构。避免这样做:
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;
}
}
}
Any reasonable explanations for this?
The compiler returns:
Error: Cannot modify members of 'ms' because it is 'foreach iteration variable'
EDIT:
Extra question:
I just tried changing a string from MyFunction
, and it doesn't actually update ms
. BUT: If I go to quickwatch and assign the same value there, it does update ms
. Why does this happen if it shouldn't even be compiling in the first place, shouldn't quickwatch throw an exception?
EDIT2:
Ok, quick watch also works on a copy of ms
, so that's why I can edit it's value, it doesn't actually alter the contents of MyPrivateVariable
.
You're using them as mutable structs. Avoid doing that:
Why are mutable structs "evil"?
这篇关于Foreach结构奇怪的编译错误在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!