本文介绍了在foreach循环变化的另一个结构内部的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 下面的代码打印(调用的MyMethod时): 0 0 0 1 我就指望它打印: 0 0 1 1 这是为什么 代码: 私人结构MYSTRUCT {公共MyInnerStruct innerStruct; } 私人结构MyInnerStruct {公众诠释柜台; 公共无效AddOne() { ++计数器; } } 公共静态无效的MyMethod() { MYSTRUCT [] = myStructs新MYSTRUCT [] {新MYSTRUCT()}; 的foreach(在myStructs VAR MYSTRUCT) { MYSTRUCT myStructCopy = MYSTRUCT; Console.WriteLine(myStruct.innerStruct.counter); Console.WriteLine(myStructCopy.innerStruct.counter); myStruct.innerStruct.AddOne(); myStructCopy.innerStruct.AddOne(); Console.WriteLine(myStruct.innerStruct.counter); Console.WriteLine(myStructCopy.innerStruct.counter); } } 解决方案 的您看到此行为的原因有,由于使用迭代变量。迭代变量是只读的,在这个意义上,在C#中,你无法修改它们(C#朗规范第8.8.4细节此 Playing with read-only mutable structs is a path to unexpected behavior. Instead of using the variable directly you are actually using a copy of the variable. Hence it's the copy that is getting incremented in the case of myStruct and not the actual value. This is why the original value remains unchanged. Eric did a rather in depth article on this topic that you can access herehttp://ericlippert.com/2008/05/14/mutating-readonly-structs/Yet another reason why you should always have immutable structs. 这篇关于在foreach循环变化的另一个结构内部的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-27 09:20