据我所知,传递参数默认是值类型。在我的示例中,第一个函数 test1 采用引用类型并拆箱,如果我做对了,它会降低性能。 但是我从来没有读到过你喜欢 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;
}
最佳答案
这里根本不涉及装箱或拆箱。 string
是引用类型——为什么要装箱?这甚至意味着什么?
即使您使用了 int
相反,不需要装箱,因为没有将值转换为实际对象。
我怀疑你对两者的理解boxing和 parameter passing有缺陷。
装箱发生在需要将值类型值转换为对象时,通常是为了将其用作接口(interface)或对象类型的变量(某处)。所以这个框:
int value = 10;
Foo(value);
...
public void Foo(object x)
{
}
... 但如果 Foo
,它不会发生被更改为 x
的类型是int
相反。
关于装箱的详细规则变得非常复杂,很难精确和准确地陈述,特别是在涉及泛型的地方,但这是基础。
关于c# - 传递参数,是否发生拆箱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9630890/