在 C# 中对值类型调用方法时是否隐式装箱

本文关键字:是否 方法 调用 类型 | 更新日期: 2023-09-27 18:34:08

假设我做了这样的事情:

int x = 5;
String s = x.ToString();

来自 Java,我会被引导认为正在对 int 值进行自动装箱,使其表现得像一个对象并在其上调用方法。但我听说在 C# 中一切都是一个对象,没有像 Java"整数"类型这样的东西。那么,变量是否被框箱到对象?或者可以直接从 C# 值类型调用方法?如何?

C# int 只是像 Java/C 中那样的 32 位空间,还是更多?提前感谢您消除我的疑虑。

在 C# 中对值类型调用方法时是否隐式装箱

int是一个结构,因此它是在堆栈上声明的,而不是堆上声明的。但是,C# 中的结构可以像类一样具有方法、属性和字段。方法 ToString() 在类型 System.Object 上定义,所有类和结构都派生自 System.Object 。所以打电话.结构上的 ToString() 不执行任何类型的装箱(将值类型更改为引用类型)。

如果你想在 c# 中看到装箱,它会像这样使用强制转换或隐式转换。

public void Testing() {
    // 5 is boxed here
    var myBoxedInt = (object)5;
    var myInt = 4;
    // myInt is boxed and sent to the method
    SomeCall(myInt);
}
public void SomeCall(object param1){}

详细说明@Igor的答案并为您提供一些细节:

此代码:

public void Test() {
    int x = 5;
    string s = x.ToString();
}

可以认为是这个假设的代码:

public void Test() {
    int x = 5;
    string s = StringInternals.ToString(x);
}
// ...
public static class StringInternals {
    public static string ToString( int x ) {
        // Standard int to -> string implementation
        // Eg, figure out how many digits there are, allocate a buffer to fit them, read out digits one at a time and convert digit to char.
    }
}