在C#中调用值类型的方法时隐式完成装箱吗?

时间:2016-02-10 18:48:19

标签: c# boxing autoboxing

假设我这样做:

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

来自Java,我会被认为正在对int值进行自动装箱,使其行为像对象并在其上调用方法。但是我听说在C#中,一切都是对象,并且没有诸如Java“Integer”类型之类的东西。那么,变量是否被装箱到Object?或者可以直接从C#值类型调用方法吗?怎么样?

C#int只是一个像Java / C一样的32位空间,还是更多?提前谢谢你清除我的疑虑。

2 个答案:

答案 0 :(得分:1)

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){}

答案 1 :(得分:0)

详细说明@ 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.
    }

}