本文介绍了可空类型不是可空类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在做与空类型一些测试,并没有工作很如我所料:
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?
推荐答案
根据该的:
这是一个空类型调用的GetType 导致装箱操作是 当类型为隐式执行 转换为对象。因此的GetType 总是返回一个类型对象 再presents的基本类型,不 可空类型。
在一个框为空的对象,只有基础类型的装箱。
When you box a nullable object, only the underlying type is boxed.
再次从 MSDN :
拳击一个非空的空值类型 拖曳值类型本身,而不是 System.Nullable它包装的价值 类型。
这篇关于可空类型不是可空类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!