首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >访问struct字段复制整个struct?

访问struct字段复制整个struct?
EN

Stack Overflow用户
提问于 2016-08-25 04:47:51
回答 1查看 144关注 0票数 0

我知道,将structs作为参数传递给方法,返回它们,或尝试将struct值赋值给变量,都会创建整个struct的副本。

现在,看看下面假设的代码:

代码语言:javascript
复制
//Regions is an array of a struct type. Color and r/g/b are structs too.

if(Regions[0].Color.r == Regions[0].Color.g && Regions[0].Color.b != 0){
  .
  ..      
}

要获得r/g/b值,遮罩下面会发生什么?只将r/g/b值复制到内存位置或整个区域三次?

EN

回答 1

Stack Overflow用户

发布于 2016-08-25 05:29:41

区域是一个结构数组。我做了一个快速的例子来检查生成的IL:

代码语言:javascript
复制
public class Program
{

    public static void Main()
    {
        Foo[] Regions = new Foo[10];

        Regions[0] = new Foo();


        if(Regions[0].Color.R == Regions[0].Color.G && Regions[0].Color.B != 0)
        {

        }


    }
}

public struct Foo
{
    public Color Color { set; get; }
}

正如您在生成的IL下面看到的那样,get_Color被调用了3次,因此颜色的值被复制了3次并被检索。

代码语言:javascript
复制
  .method public hidebysig static void  Main() cil managed
  {
    // 
    .maxstack  3
    .locals init (valuetype Foo[] V_0,
             valuetype [System.Drawing]System.Drawing.Color V_1,
             bool V_2)
    IL_0000:  nop
    IL_0001:  ldc.i4.s   10
    IL_0003:  newarr     Foo
    IL_0008:  stloc.0
    IL_0009:  ldloc.0
    IL_000a:  ldc.i4.0
    IL_000b:  ldelema    Foo
    IL_0010:  initobj    Foo
    IL_0016:  ldloc.0
    IL_0017:  ldc.i4.0
    IL_0018:  ldelema    Foo
    IL_001d:  call       instance valuetype [System.Drawing]System.Drawing.Color Foo::get_Color()
    IL_0022:  stloc.1
    IL_0023:  ldloca.s   V_1
    IL_0025:  call       instance uint8 [System.Drawing]System.Drawing.Color::get_R()
    IL_002a:  ldloc.0
    IL_002b:  ldc.i4.0
    IL_002c:  ldelema    Foo
    IL_0031:  call       instance valuetype [System.Drawing]System.Drawing.Color Foo::get_Color()
    IL_0036:  stloc.1
    IL_0037:  ldloca.s   V_1
    IL_0039:  call       instance uint8 [System.Drawing]System.Drawing.Color::get_G()
    IL_003e:  bne.un.s   IL_0059

    IL_0040:  ldloc.0
    IL_0041:  ldc.i4.0
    IL_0042:  ldelema    Foo
    IL_0047:  call       instance valuetype [System.Drawing]System.Drawing.Color Foo::get_Color()
    IL_004c:  stloc.1
    IL_004d:  ldloca.s   V_1
    IL_004f:  call       instance uint8 [System.Drawing]System.Drawing.Color::get_B()
    IL_0054:  ldc.i4.0
    IL_0055:  ceq
    IL_0057:  br.s       IL_005a

    IL_0059:  ldc.i4.1
    IL_005a:  nop
    IL_005b:  stloc.2
    IL_005c:  ldloc.2
    IL_005d:  brtrue.s   IL_0061

    IL_005f:  nop
    IL_0060:  nop
    IL_0061:  ret
  } // end of method Program::Main
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39136853

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档