c# - 通过 ref - 内存占用在堆栈上传递 'value type'

标签 c# .net memory

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

必须在某处创建临时值/指针以在方法完成时更改原始值。有人可以解释一下或指出答案吗 - 内存中有很多东西,但似乎没有人回答这个问题。型

最佳答案

如果你有这样的方法:

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/

相关文章:

c# - Visual Studio 2015 双击状态栏中的行号不起作用

c# - 奇怪的自定义操作

c# - 用于处理 Ajax 弹出窗口的 Watin 脚本

将字符串复制到动态二维数组中

c# - 如何为 Ubuntu 12.04 开发 C#.NET 应用程序

c# - 在 EF Code First 中,是否可以封装应该持久保存到数据存储的属性?

.net - 如何使用包含辅助方法的 .cshtml 文件创建 nuget 包

c# - 为什么 Live Connect SignInButton 因无效的 redirect_uri 而失败?

javascript - 我们如何测试 `div.innerHTML=""` 是否会占用内存,直到页面刷新或浏览器关闭?

Android:将外部存储器上的文件夹设为私有(private)或 protected