在foreach循环变化的另一个结构内部的结构 [英] Changing a struct inside another struct in a foreach loop

查看:237
本文介绍了在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细节此




迭代变量对应于一个只读的局部变量与延伸到嵌入语句


A范围

具有只读可变结构播放是路径意外的行为,而是直接使用变量,你实际上是使用变量的副本,因此它是在 MYSTRUCT 的情况下得到增加的副本,而不是的实际值,这就是为什么原来的值保持不变。



埃里克做了这个话题,您可以访问这里。


相当深入的文章


另一个原因,你应该< STRONG>总是有一成不变的结构。


The following code prints (when invoking MyMethod):

0
0
0
1

I would expect it to print:

0
0
1
1

Why is this?

Code:

private struct MyStruct
{
    public MyInnerStruct innerStruct;
}

private struct MyInnerStruct
{
    public int counter;

    public void AddOne()
    {
        ++counter;
    }
}

public static void MyMethod()
{
    MyStruct[] myStructs = new MyStruct[] { new MyStruct() };

    foreach (var myStruct in myStructs)
    {
        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);
    }
}

解决方案

The reason you are seeing this behavior has to due with using an iteration variable. Iteration variables are read-only in the sense that in C# you cannot modify them (C# lang spec section 8.8.4 details this

The iteration variable corresponds to a read-only local variable with a scope that extends over the embedded statement

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 here

Yet another reason why you should always have immutable structs.

这篇关于在foreach循环变化的另一个结构内部的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆