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

我想做的是这样的:

switch( myObject.GetType().GetProperty( "id") ) { case ??: // when Nullable, do this case ??: // when string, do this case ??: // when Nullable, do this 

object.GetType()下的什么路径将具有我可以使用case语句进行比较的数据类型的字符串名称? 我需要知道类型,所以我可以使用许多Convert.ToInt32(字符串)中的一个,它将使用Reflection设置myObject的值。

更新:看起来C#7将支持切换Type s,因为这个问题的提问者正试图这样做。 虽然注意语法地雷,但它有点不同。

您不需要字符串名称来比较它:

 if (myObject.GetType().GetProperty("id").PropertyType == typeof(Nullable)) // when Nullable, do this else if (myObject.GetType().GetProperty("id").PropertyType == typeof(string)) // when string, do this else if (myObject.GetType().GetProperty("id").PropertyType == typeof(Nullable)) // when Nullable, do this 

我一直在使用以下类型的代码来检查类型是否可以为空并获取实际类型:

 if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { return Nullable.GetUnderlyingType(type); } 

如果类型是例如Nullable,则此代码返回int部分(基础类型)。 如果只需要将对象转换为特定类型,则可以使用System.Convert.ChangeType方法。

这个问题非常令人困惑。 “myObject”是否可能是一个可以为空的int? 或者属性“id”可能是类型为nullable int?

如果是前者,你的问题无法回答,因为它预示着虚假。 没有像盒装的可空int那样的东西。 我注意到所有提出if (myobject.GetType() == typeof(int?))的答案都是错误的; 这种情况永远不会成真。

当你将一个可空的int转换为object时,要么它变成一个空引用(如果nullable int没有值),或者它变成一个盒装的int。 无法确定对象是否包含可为空的int,因为对象永远不会包含可为空的int。

如果是后者,请将属性类型typeof(int?) 。 你不能使用开关; 只有常量可用于开关案例,类型不是常量。

总而言之,这是一个糟糕的代码味道。 为什么你首先使用reflection?

在.net中,值类型的实例只是位的集合,没有关联的类型信息。 但是,对于除Nullable之外的每个值类型,系统还会自动生成从System.ValueType派生的相应类类型。 存在从值类型到自动生成的类类型的扩展转换,以及从自动生成的类类型到值类型的缩小转换。 在Nullable的情况下,没有相应的自动生成的类类型,其中包含与值类型的转换; 相反,在Nullable和与T相关联的类类型之间的两个方向上存在加宽转换。

据我所知,实现了这种奇怪的行为,以允许null和空Nullable之间的比较返回true。

正如@Cody Gray所说,如果陈述可能是最好的方式

 var t = myObject.GetType(); if (t == typeof(Nullable)) { } else if (t == typeof(string)) {} else if (t==typeof(Nullable)) {}