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

前端 未结 5 1441
情书的邮戳
情书的邮戳 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:40

    declarations of variable is compile time only information whereas method execution is runtime. In other words there's no way GetType() can know what type the object was declared as it can only know the actual type of the object at runtime.

    similar if you had

    class a
    {
    }
    
    class b : a
    
    a bInstance = new b();
    bInstance.GetType();
    

    the call to bInstance.GetType() have no way of knowing that the variable was declared as type 'a' and I don't think you expect it to return 'a' in this case either. However in the example above a is my abbreviation of object and b is for System.Int32

提交回复
热议问题