加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在C#中Foreach结构奇怪的编译错误

发布时间:2020-12-15 20:48:30 所属栏目:百科 来源:网络整理
导读:namespace MyNamespace{ public struct MyStruct { public string MyString; public int MyInt; public bool MyBool; } public class MyClass { private ListMyStruct MyPrivateVariable; public ListMyStruct MyVariable { get { if (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;
        }
    }
}

对此有任何合理的解释吗?

编译器返回:

Error:
Cannot modify members of ‘ms’ because it is ‘foreach iteration
variable’

编辑:

额外的问题:

我只是尝试从MyFunction更改一个字符串,它实际上并没有更新ms.但是:如果我去快速观察并在那里分配相同的值,它会更新ms.如果它首先不应该编译,为什么会发生这种情况,不应该快速观察异常?

EDIT2:

好的,快速监视也适用于ms的副本,这就是为什么我可以编辑它的值,它实际上并没有改变MyPrivateVariable的内容.

解决方法

你正在使用它们作为可变结构.避免这样做:

Why are mutable structs “evil”?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读