相关疑难解决方法(0)

C#反思:如何获取Nullable <int>的类型?

我想做的是这样的:

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的值.

.net c# reflection typeof gettype

29
推荐指数
3
解决办法
2万
查看次数

IsPrimitive不包含可空的原始值

我想检查Type是否是原始的,并使用以下代码:

return type.IsValueType && type.IsPrimitive;
Run Code Online (Sandbox Code Playgroud)

只要原语不可为空,这就可以正常工作.例如int ?,如何检查类型是否为可为空的原始类型?(仅供参考:type.IsPrimitive == false在int?)

c# primitive types

12
推荐指数
2
解决办法
5136
查看次数

为什么((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
查看次数

如何初始化 System.Nullable&lt;Int32&gt;?

我需要一个 Nullable 类型,但如何初始化这样的变量?每当我尝试这样做时,它会自动转换为普通的 Int32。

Nullable<Int32> nullableInt32 = new Nullable<Int32>(3);
Console.WriteLine(nullableInt32.GetType()); // gives me System.Int32
Run Code Online (Sandbox Code Playgroud)

这是一个错误吗?我怎样才能真正初始化 Nullable?

.net c#

1
推荐指数
1
解决办法
56
查看次数

标签 统计

c# ×4

.net ×3

.net-4.0 ×1

gettype ×1

nullable ×1

primitive ×1

reflection ×1

typeof ×1

types ×1