当我们通过引用传递一个存储在堆栈上的值类型时,内存中会发生什么?
必须在某个位置创建临时值/指针,以便在方法完成时更改原始值。有没有人可以解释一下或者给我指出答案--记忆中有很多东西,但似乎没有一个人回答这个问题。ty
发布于 2009-08-25 17:58:39
如果你有一个像这样的方法:
static void Increment(ref int value)
{
value = value + 1;
}然后这样叫它:
int value = 5;
Increment(ref value);然后,不是将值5推入堆栈,而是将变量value的位置推入堆栈。也就是说,Increment直接更改value的内容,而不是在方法完成后更改。
下面是方法和方法调用的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
}发布于 2009-08-25 17:57:25
这听起来像是你在寻找一些关于装箱和拆箱的细节,这两个术语用于描述将值类型视为引用类型。
有很多文章描述了这个过程,我会试着找到一些像样的--but here's one for starters。
https://stackoverflow.com/questions/1329889
复制相似问题