typeof(DateTime?)。Name == Nullable`1
在.Net typeof(DateTime?).Name
使用Reflection typeof(DateTime?).Name
返回“Nullable`1”。
有没有办法将实际类型作为字符串返回。 (在本例中为“DateTime”或“System.DateTime”)
我明白DateTime?
是Nullable
。 除此之外,我只是在寻找可空类型的类型。
在这种情况下,有一个Nullable.GetUnderlyingType
方法可以帮助您。 可能你最终想要制作自己的实用方法,因为(我假设)你将使用可空和非可空类型:
public static string GetTypeName(Type type) { var nullableType = Nullable.GetUnderlyingType(type); bool isNullableType = nullableType != null; if (isNullableType) return nullableType.Name; else return type.Name; }
用法:
Console.WriteLine(GetTypeName(typeof(DateTime?))); //outputs "DateTime" Console.WriteLine(GetTypeName(typeof(DateTime))); //outputs "DateTime"
编辑:我怀疑你也可能在类型上使用其他机制,在这种情况下,您可以稍微修改它以获取基础类型或使用现有类型,如果它不可为空:
public static Type GetNullableUnderlyingTypeOrTypeIfNonNullable(this Type possiblyNullableType) { var nullableType = Nullable.GetUnderlyingType(possiblyNullableType); bool isNullableType = nullableType != null; if (isNullableType) return nullableType; else return possiblyNullableType; }
对于一种方法来说,这是一个可怕的名字,但我不够聪明,想出一个方法(如果有人建议更好的话,我会很乐意改变它!)
然后作为扩展方法,您的用法可能如下:
public static string GetTypeName(this Type type) { return type.GetNullableUnderlyingTypeOrTypeIfNonNullable().Name; }
要么
typeof(DateTime?).GetNullableUnderlyingTypeOrTypeIfNonNullable().Name
正如Patryk指出的那样:
typeof(DateTime?).GetGenericArguments()[0].Name
Chris Sinclair代码可以工作,但我更简洁地重写了它。
public static Type GetNullableUnderlyingTypeIfNullable(Type possiblyNullableType) { return Nullable.GetUnderlyingType(possiblyNullableType) ?? possiblyNullableType; }
然后使用它:
GetNullableUnderlyingTypeIfNullable(typeof(DateTime?)).Name