如果 typeof(int?) 是 Int32,那么 Nullable.GetUnderlyingType 有什么用? [英] Whats the use of Nullable.GetUnderlyingType, if typeof(int?) is an Int32?

查看:76
本文介绍了如果 typeof(int?) 是 Int32,那么 Nullable.GetUnderlyingType 有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 typeof int?Int32

int? x = 1;
Console.WriteLine(x.GetType().Name);

如果可以,那么Nullable.GetUnderlyingType有什么用?

If it is okay then what's the use of Nullable.GetUnderlyingType?

推荐答案

调用 GetType() 框你的变量.CLR 有一个特殊规则,Nullable 被装箱到 T.所以 x.GetType 将返回 Int32 而不是 Nullable.

Calling GetType() boxes your variable. The CLR has a special rule that Nullable<T> gets boxed to T. So x.GetType will return Int32 instead of Nullable<Int32>.

int? x = 1;
x.GetType() //Int32
typeof(int?) //Nullable<Int32>

由于包含 nullNullable 将被装箱为 null,因此以下将抛出异常:

Since a Nullable containing null will be boxed to null the following will throw an exception:

int? x = null;
x.GetType() //throws NullReferenceException

引用 MSDN on Boxing Nullable Types:

基于可为空类型的对象仅在对象非空时才装箱.如果 HasValuefalse,则对象引用被分配给 null 而不是装箱

Objects based on nullable types are only boxed if the object is non-null. If HasValue is false, the object reference is assigned to null instead of boxing

如果对象不为空——如果HasValuetrue——然后​​装箱发生,但只有可空对象所基于的基础类型被装箱.装箱非空的可为空值类型装箱值类型本身,而不是包装值类型的 System.Nullable.

If the object is non-null -- if HasValue is true -- then boxing occurs, but only the underlying type that the nullable object is based on is boxed. Boxing a non-null nullable value type boxes the value type itself, not the System.Nullable<T> that wraps the value type.

这篇关于如果 typeof(int?) 是 Int32,那么 Nullable.GetUnderlyingType 有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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