可空类型不是可空类型? [英] Nullable type is not a nullable type?

查看:220
本文介绍了可空类型不是可空类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做与空类型一些测试,并没有工作很如我所料:

I was doing some testing with nullable types, and it didn't work quite as I expected:

int? testInt = 0;
Type nullableType = typeof(int?);
Assert.AreEqual(nullableType, testInt.GetType()); // not the same type

这也不行:

DateTime? test = new DateTime(434523452345);
Assert.IsTrue(test.GetType() == typeof(Nullable)); //FAIL 

DateTime? test = new DateTime(434523452345);
Assert.IsTrue(test.GetType() == typeof(Nullable<>)); //STILL FAIL

我的问题是为什么testInt.GetType()返回int和typeof运算(INT?)返回真正的可空类型?

My question is why does testInt.GetType() return int, and typeof(int?) return the true nullable type?

推荐答案

根据该的 MSDN

这是一个空类型调用的GetType   导致装箱操作是   当类型为隐式执行   转换为对象。因此的GetType   总是返回一个类型对象   再presents的基本类型,不   可空类型。

Calling GetType on a Nullable type causes a boxing operation to be performed when the type is implicitly converted to Object. Therefore GetType always returns a Type object that represents the underlying type, not the Nullable type.

在一个框为空的对象,只有基础类型的装箱。

When you box a nullable object, only the underlying type is boxed.

再次从 MSDN

拳击一个非空的空值类型   拖曳值类型本身,而不是   System.Nullable它包装的价值   类型。

Boxing a non-null nullable value type boxes the value type itself, not the System.Nullable that wraps the value type.

这篇关于可空类型不是可空类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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