我想做的是这样的:
switch( myObject.GetType().GetProperty( "id") )
{
case ??:
// when Nullable<Int32>, do this
case ??:
// when string, do this
case ??:
// when Nullable<bool>, do this
Run Code Online (Sandbox Code Playgroud)
object.GetType()下的什么路径将具有我可以使用case语句进行比较的数据类型的字符串名称?我需要知道类型,所以我可以使用许多Convert.ToInt32(字符串)中的一个,它将使用Reflection设置myObject的值.
我想检查Type是否是原始的,并使用以下代码:
return type.IsValueType && type.IsPrimitive;
Run Code Online (Sandbox Code Playgroud)
只要原语不可为空,这就可以正常工作.例如int ?,如何检查类型是否为可为空的原始类型?(仅供参考:type.IsPrimitive == false在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编译和运行等代码就好了.
为什么铸造int到int?返回int?
请注意,如果我1用一些int-variable 替换constant(),这也适用.
我需要一个 Nullable 类型,但如何初始化这样的变量?每当我尝试这样做时,它会自动转换为普通的 Int32。
Nullable<Int32> nullableInt32 = new Nullable<Int32>(3);
Console.WriteLine(nullableInt32.GetType()); // gives me System.Int32
Run Code Online (Sandbox Code Playgroud)
这是一个错误吗?我怎样才能真正初始化 Nullable?