相关疑难解决方法(0)

可空类型不是可以为空的类型?

我正在使用可空类型进行一些测试,并且它没有像我预期的那样工作:

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

这也不起作用:

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
Run Code Online (Sandbox Code Playgroud)

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

.net c# nullable gettype

44
推荐指数
2
解决办法
4423
查看次数

为什么((int?)1).GetType()返回typeof(int)?

可能重复:
Nullable类型不是可空类型?
为什么GetType返回System.Int32而不是Nullable <Int32>?

我期望((int?) 1).GetType()回来typeof(int?),但事实证明它返回typeof(int):

bool a = ((int?)1).GetType() == typeof(int?); // a is false
bool b = ((int?)1).GetType() == typeof(int); // b is true
Run Code Online (Sandbox Code Playgroud)

仍然,((int?) 1).HasValue编译和运行等代码就好了.

为什么铸造intint?返回int

请注意,如果我1用一些int-variable 替换constant(),这也适用.

.net c# nullable .net-4.0

8
推荐指数
0
解决办法
347
查看次数

标签 统计

.net ×2

c# ×2

nullable ×2

.net-4.0 ×1

gettype ×1