当我们通过引用传递值类型(已存储在堆栈中)时,内存中会发生什么?

该方法完成后,必须在某处创建临时值/指针以更改原始值.有人可以解释一下或为我指出答案吗?记忆中有很多东西,但似乎没人回答. ty

解决方法:

如果您有这样的方法:


static void Increment(ref int value)
{
   value = value + 1;
}

并这样称呼它:

int value = 5;
Increment(ref value);

那么发生的是,不是将值5压入堆栈,而是将变量值的位置压入堆栈.即值的内容直接由Increment更改,而不是在方法完成后更改.

这分别是方法的IL和方法调用:

.method private hidebysig static void Increment(int32& 'value') cil managed
{
    .maxstack 8
    L_0000: nop 
    L_0001: ldarg.0 
    L_0002: ldarg.0 
    L_0003: ldind.i4         // loads the value at the location of 'value'
    L_0004: ldc.i4.1 
    L_0005: add 
    L_0006: stind.i4         // stores the result at the location of 'value'
    L_0007: ret 
}

.method private hidebysig static void Main() cil managed
{
    .entrypoint
    .maxstack 9
    .locals init ([0] int32 value) //   <-- only one variable declared
    L_0000: nop 
    L_0001: ldc.i4.5
    L_0002: stloc.0 
    L_0003: ldloca.s 'value'   // call Increment with the location of 'value'
    L_0005: call void Program::Increment(int32&)
    L_000a: ret 
}

标签: memory, c, net

相关文章推荐

添加新评论,含*的栏目为必填