我知道,将structs作为参数传递给方法,返回它们,或尝试将struct值赋值给变量,都会创建整个struct的副本。
现在,看看下面假设的代码:
//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值复制到内存位置或整个区域三次?
发布于 2016-08-25 05:29:41
区域是一个结构数组。我做了一个快速的例子来检查生成的IL:
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次并被检索。
.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::Mainhttps://stackoverflow.com/questions/39136853
复制相似问题