c# - 传递参数,是否发生拆箱

标签 c# .net

据我所知,传递参数默认是值类型。在我的示例中,第一个函数 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相反,不需要装箱,因为没有将值转换为实际对象。

我怀疑你对两者的理解boxingparameter passing有缺陷。

装箱发生在需要将值类型值转换为对象时,通常是为了将其用作接口(interface)或对象类型的变量(某处)。所以这个框:

int value = 10;
Foo(value);

...

public void Foo(object x)
{
}

... 但如果 Foo,它不会发生被更改为 x 的类型是int相反。

关于装箱的详细规则变得非常复杂,很难精确和准确地陈述,特别是在涉及泛型的地方,但这是基础。

关于c# - 传递参数,是否发生拆箱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9630890/

相关文章:

c# - 如何在单元测试中从 Automapper 模拟 IValueResolver 的依赖关系

C# 相当于 Java 的 DigestUtils.md5Hex(String)?

.net - 正则表达式:查找整个模式,部分替换

c# - Net Core : Execute All Dependency Injection in Xunit Test for AppService, 存储库等

c# - Gui 异步操作模式?

c# - IEnumerable 和数组的关系

c# - 使用 for 循环获取动态创建的 asp 控件 ids(values)

c# - ASP.NET - CSS 到 ImageButton 下的中心标签?

c# - 混淆/随机化字符串

c# - 按返回类型重载?