boxing and unboxing, why aren't the outputs both “System.Object”?

前端 未结 5 1447
情书的邮戳
情书的邮戳 2021-02-15 15:45

I got the following code:

object var3 = 3;
Console.WriteLine(var3.GetType().ToString());
Console.WriteLine(typeof(object).ToString());

The outp

5条回答
  •  孤独总比滥情好
    2021-02-15 16:45

    Ignoring the topic of boxing, all classes inherit from type object. This is true for both reference types and value types. GetType shows the most derived type, which in this case is System.Int32.

    One of the few times GetType is going to return System.Object is if you do this:

    object var = new Object();
    Console.WriteLine(var.GetType().ToString());
    

    Boxing refers to when a value type is pointed to by a reference type. Generally this is done as a System.Object reference. TypeOf will return the most derived actual type, not the reference type.

    class A
    {
    }
    
    class B : A
    {
    }
    
    class C : B
    {
    }
    
    object obj1 = new ClassA();
    ClassB obj2 = new ClassB();
    ClassB obj3 = new ClassC();
    

    GetType will do similar things for these types.

    System.Console.WriteLine(obj1.GetType().ToString());
    System.Console.WriteLine(obj2.GetType().ToString());
    System.Console.WriteLine(obj3.GetType().ToString());
    

    ClassA
    ClassB
    ClassC

提交回复
热议问题