int? 竟然真的可以是 null!.NET/C# 确定可空值类型 Nullable 实例的真实类型
使用 Nullable 我们可以为原本不可能为 null 的值类型像引用类型那样提供一个 null 值。不过注意:Nullable 本身也是个 struct,是个值类型哦。这意味着你随时可以调用 .HasValue 这样的方法,而不用担心会出现 NullReferenceException。
等等!除了本文提到的一些情况。
本文内容
- Nullable 中的 null
- Object.GetType() 和 is 对 Nullable 的作用
- 应该如何判断可空值类型的真实类型
- 参考资料
docs.microsoft.com 中,有一段对此的描述:
When you call the Object.GetType method on an instance of a nullable type, the instance is boxed to Object. As boxing of a non-null instance of a nullable type is equivalent to boxing of a value of the underlying type, GetType returns a Type object that represents the underlying type of a nullable type.
When you call the Object.GetType method on an instance of a nullable type, the instance is boxed to Object. As boxing of a non-null instance of a nullable type is equivalent to boxing of a value of the underlying type, GetType returns a Type object that represents the underlying type of a nullable type.
意思是说,当你对一个可空值类型 Nullable 调用 Object.GetType() 方法的时候,这个实例会被装箱,会被隐式转换为一个 object 对象。然而对可空值类型的装箱与对值类型本身的装箱是同样的操作,所以调用 GetType() 的时候都是返回这个对象对应的实际基础类型。例如对一个 int? 进行装箱和对 int 装箱得到的 object 对象是一样的,于是 GetType() 实际上是不能区分这两种情况的。
那什么样的装箱会使得两个不同的类型被装箱为同一个了呢?
另一篇文档描述了 Nullable 装箱的过程:
- If HasValue returns false, the null reference is produced.
- If HasValue returns true, a value of the underlying value type T is boxed, not the instance of Nullable.
- 如果
HasValue返回false,那么就装箱一个null - 如果
HasValue返回true,那么就将Nullable中的T进行装箱,而不是Nullable的实例。
这才是为什么 GetType() 会得到以上结果的原因。
同样的,也不能使用 is 运算符来确定这个类型到底是不是可空值类型:
Console.WriteLine($"value is int = {value is int}");
Console.WriteLine($"value is int? = {value is int?}");
最终得到两者都是 True。

c# - Nullable type is not a nullable type? - Stack Overflow
我的博客会首发于 https://walterlv.com/,而 CSDN 和博客园仅从其中摘选发布,而且一旦发布了就不再更新。

本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。欢迎转载、使用、重新发布,但务必保留文章署名吕毅(包含链接:https://blog.csdn.net/wpwalter),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请与我联系。