传递参数,会发生拆箱

Sim*_*röm 2 .net c#

我读过的,传递参数是默认的valuetypes.在我的例子中,第一个函数test1采用引用类型和unbox,如果我做对了,它会降低性能.但是我从来没有读过你喜欢test2来提高性能.

那么最佳做法是什么?

public Main(){
    string test = "hello";
    test1(test); // Does this line perform a boxing? So it's not good for performance?
    test2(ref test); // Passing a reference as a reference
}

public string test1(string arg1) {
    return arg1;
}

public string test2(ref string arg1) {
    return arg1;
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

这里根本没有拳击或拆箱.string是一种参考类型 - 它为什么会被装箱?这甚至意味着什么?

即使您使用了int,也不需要装箱,因为没有将值转换为实际对象.

我怀疑你对拳击参数传递的理解是有缺陷的.

当需要将值类型值转换为对象时,通常是为了将其用作接口或对象类型的变量(某处)时发生限制.所以这个方框:

int value = 10;
Foo(value);

...

public void Foo(object x)
{
}
Run Code Online (Sandbox Code Playgroud)

...但它不会在发生Foo了改变,使得该类型xint不是.

关于拳击的详细规则变得非常复杂,以准确和准确地陈述,特别是在泛型进入的情况下,但这是基础.


Mar*_*ell 5

这里根本没有拳击; 装箱时将值类型视为object或接口(不包括泛型),例如:

int i = 1;
Foo(i); // the value of i is boxed
Bar(i); // the value of i is boxed
...
private void Foo(object obj) {...}
private void Bar(IConvertible obj) {...}
Run Code Online (Sandbox Code Playgroud)

在你的例子中,a:这里没有类型转换,所以不需要框,而b:string无论如何都是引用类型,所以没有拳击字符串的含义.

test2实际上显示的是"通过引用传递",也就是说ref,它与装箱完全无关 - 实际上ref参数必须是精确匹配,因此参数中不会涉及任何装箱ref(但是,后续代码可以参考中获取值)然后盒/ unbox )