int ref参数会被装箱吗? [英] Do int ref parameter get boxed?

查看:39
本文介绍了int ref参数会被装箱吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下代码:

void Main()
{
    int a = 5;
    f1(ref a);
}

public void f1(ref int a)
{
    if(a > 7) return;
    a++;
    f1(ref a);
    Console.WriteLine(a);
}

输出为:

8 8 8 

,当堆栈展开时,将保留ref参数的值.

i.e. when the stack unwinds the value of the ref parameter is maintained.

这是否意味着在 int参数中添加 ref关键字导致将其装箱?
在递归调用过程中,实际堆栈看起来如何?

Does it mean that adding ref keyword to int parameter causes it to get boxed?
How does the actual stack look like during the recursive call?

推荐答案

通过引用传递值类型会导致其在栈中的 position 而不是值本身传递.它与装箱拆箱没有关系.这使得思考递归调用期间堆栈的外观变得相当容易,因为每个单个调用都指向堆栈上的相同"位置.

Passing a value type by reference causes its position on the stack to get passed rather than the value itself. It has nothing to do with boxing and unboxing. This makes thinking about how the stack looks during the recursive calls rather easy, as every single call refers to the "same" location on the stack.

我认为, MSDN关于拳击和取消装箱:

装箱是过程的名称,将值类型转换为引用类型.将变量装箱时,将创建一个引用变量,该引用变量指向堆上的新副本.引用变量是一个对象,...

Boxing is name given to the process whereby a value type is converted into a reference type. When you box a variable, you are creating a reference variable that points to a new copy on the heap. The reference variable is an object, ...

可能会在两个不同的事物之间使您感到困惑: 1)如您所愿,将"<值>值类型" 转换"为一个对象,根据定义,该对象是一个引用类型:

Possibly confusing you between two different things: 1) the "converting" as you will, of a value type to say an object, which is by definition a reference type:

int a = 5;
object b = a; // boxed into a reference type

2),并通过引用传递值类型参数 :

and 2) with the passing of a value type parameter by reference:

main(){
   int a = 5;
   doWork(ref a);
}
void doWork(ref int a)
{
    a++;
}

有两件事.

这篇关于int ref参数会被装箱吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆