如果每个元素都是结构数组,foreach会复制每个元素吗? [英] Does foreach copy each element if it is an array of structs?

查看:45
本文介绍了如果每个元素都是结构数组,foreach会复制每个元素吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构体数组.遍历数组时, foreach 运算符是否会复制每个元素?据我了解, foreach 只是在语法上转换为 for 的语法糖.因此看来答案是否定的,但我希望得到一些确认.

I have an array of structs. Does foreach operator make a copy of each element when iterating thru an array? As far as I understand foreach is just syntactic sugar under the hood converted to for. So it appears the answer is no but I'd love to have some confirmation.

PS:看来有人应该已经问过了,但是我很难找到任何东西.因此,请以提供参考的方式投票作为dup.

PS: it appears someone should have already asked that but I can't easily find anything. So please vote as a dup with provided reference.

推荐答案

是的,将创建值类型实例的副本.遍历数组时, foreach 确实会使用数组访问而不是使用枚举器,但是每个数组插槽中的值仍会被复制.

Yes, copies of the value type instances will be made. When iterating over an array, foreach will indeed use array accesses instead of using an enumerator, but the value in each array slot is still copied.

此代码:

struct AStruct
{
    public string a;
    public int b;

    static void Main()
    {
        var structs = new AStruct[10];

        foreach (var x in structs) {
            Console.WriteLine(x);
        }
    }
}

Main()方法生成以下IL:

.method private static hidebysig
       default void Main ()  cil managed
{
    .entrypoint
    .maxstack 4
    .locals init (
            valuetype AStruct[]     V_0,
            valuetype AStruct[]     V_1,
            int32   V_2,
            valuetype AStruct       V_3)
    IL_0000:  ldc.i4.s 0x0a
    IL_0002:  newarr AStruct
    IL_0007:  stloc.0
    IL_0008:  ldloc.0
    IL_0009:  stloc.1
    IL_000a:  ldc.i4.0
    IL_000b:  stloc.2
    IL_000c:  br IL_002d

    IL_0011:  ldloc.1
    IL_0012:  ldloc.2
    IL_0013:  ldelema AStruct
    IL_0018:  ldobj AStruct
    IL_001d:  stloc.3
    IL_001e:  ldloc.3
    IL_001f:  box AStruct
    IL_0024:  call void class [mscorlib]System.Console::WriteLine(object)
    IL_0029:  ldloc.2
    IL_002a:  ldc.i4.1
    IL_002b:  add
    IL_002c:  stloc.2
    IL_002d:  ldloc.2
    IL_002e:  ldloc.1
    IL_002f:  ldlen
    IL_0030:  conv.i4
    IL_0031:  blt IL_0011

    IL_0036:  ret
} // end of method AStruct::Main

请注意指令IL_0013至IL_001d.每个数组插槽上的整个值都被压入堆栈,并存储在本地V_3中( x 迭代变量).

Note the instructions IL_0013 through IL_001d. The entire value at each array slot is pushed onto the stack and stored in the local V_3 (the x iteration variable).

这篇关于如果每个元素都是结构数组,foreach会复制每个元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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