当我们通过引用传递一个存储在堆栈中的值类型时,内存中会发生什么?
必须在某处创建临时值/指针以在方法完成时更改原始值。有人可以解释一下或指出答案吗 - 内存中有很多东西,但似乎没有人回答这个问题。型
最佳答案
如果你有这样的方法:
static void Increment(ref int value)
{
value = value + 1;
}
并这样调用它:
int value = 5;
Increment(ref value);
然后发生的事情是,变量 value
的位置被压入堆栈,而不是值 5 被压入堆栈。 IE。 value
的内容由 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
}
关于c# - 通过 ref - 内存占用在堆栈上传递 'value type',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1329889/