为什么 GetType 返回 System.Int32 而不是 Nullable<Int32>? [英] Why GetType returns System.Int32 instead of Nullable&lt;Int32&gt;?

查看:27
本文介绍了为什么 GetType 返回 System.Int32 而不是 Nullable<Int32>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这个片段的输出是 System.Int32 而不是 Nullable?

Why is the output of this snippet System.Int32 instead of Nullable<Int32>?

int? x = 5;
Console.WriteLine(x.GetType());

推荐答案

GetType()object的一个方法.
要调用它,必须将 Nullable 结构装箱.

GetType() is a method of object.
To call it, the Nullable<T> struct must be boxed.

您可以在 IL 代码中看到这一点:

You can see this in the IL code:

//int? x = 5;
IL_0000:  ldloca.s    00 
IL_0002:  ldc.i4.5    
IL_0003:  call        System.Nullable<System.Int32>..ctor

//Console.WriteLine(x.GetType());
IL_0008:  ldloc.0     
IL_0009:  box         System.Nullable<System.Int32>
IL_000E:  callvirt    System.Object.GetType
IL_0013:  call        System.Console.WriteLine

Nullable 类型被 CLR 特殊处理;不可能有可空类型的盒装实例.
相反,装箱可空类型将导致空引用(如果 HasValue 为假)或装箱值(如果有值).

Nullable types are treated specially by CLR; it is impossible to have a boxed instance of a nullable type.
Instead, boxing a nullable type will result in a null reference (if HasValue is false), or the boxed value (if there is a value).

因此,box System.Nullable<System.Int32> 指令会生成一个装箱的 Int32,而不是装箱的 Nullable.

Therefore, the box System.Nullable<System.Int32> instruction results in a boxed Int32, not a boxed Nullable<Int32>.

因此,GetType() 不可能永远返回Nullable.

要更清楚地看到这一点,请查看以下代码:

To see this more clearly, look at the following code:

static void Main()
{
    int? x = 5;
    PrintType(x);   
}
static void PrintType<T>(T val) {
    Console.WriteLine("Compile-time type: " + typeof(T));
    Console.WriteLine("Run-time type: " + val.GetType());
}

这个打印

编译时类型:System.Nullable`1[System.Int32]
运行时类型:System.Int32

Compile-time type: System.Nullable`1[System.Int32]
Run-time type: System.Int32

这篇关于为什么 GetType 返回 System.Int32 而不是 Nullable<Int32>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆