C# typeof(DateTime?).Name==Nullable`1
在.NetC# typeof(DateTime?).Name==Nullable`1,c#,.net,system.reflection,C#,.net,System.reflection,在.Nettypeof(DateTime?)中使用反射。Name返回“Nullable`1” 是否有任何方法可以将实际类型作为字符串返回。(在本例中为“DateTime”或“System.DateTime”) 我知道DateTime?可以为空。除此之外,我只是在寻找可空类型的类型。正如Patryk所指出的: typeof(DateTime?).GetGenericArguments()[0]。Name在这种情况下,有一种方法可以帮助您。很可能您最终会想要创建自己的实用程序方法,因为(我假设)您将
typeof(DateTime?)中使用反射。Name
返回“Nullable`1”
是否有任何方法可以将实际类型作为字符串返回。(在本例中为“DateTime”或“System.DateTime”)
我知道
DateTime?
可以为空。除此之外,我只是在寻找可空类型的类型。正如Patryk所指出的:
typeof(DateTime?).GetGenericArguments()[0]。Name
在这种情况下,有一种方法可以帮助您。很可能您最终会想要创建自己的实用程序方法,因为(我假设)您将同时使用可为null和不可为null的类型:
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"
编辑:我怀疑您可能还在该类型上使用其他机制,在这种情况下,您可以稍微修改它以获得基础类型,或者使用现有类型(如果它不可为null):
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;
}
或
Chris Sinclair代码可以工作,但我重写的代码更简洁
public static Type GetNullableUnderlyingTypeIfNullable(Type possiblyNullableType)
{
return Nullable.GetUnderlyingType(possiblyNullableType) ?? possiblyNullableType;
}
然后使用它:
GetNullableUnderlyingTypeIfNullable(typeof(DateTime?)).Name
实际类型是可空的
去掉问号。请记住,作为测试,删除代码中的问号可能会破坏某些东西。如果要通过反射选择泛型类型名称,在这种情况下,如果每次都是泛型类型,则必须使用GetGenericArguments()[0]
,如果不是,你必须检查它。唯一的问题是,如果在实践中,它是一种获取类型的通用方法,这也会为List
@ChrisSinclair等类型提取泛型类型。你可以简单地添加一个检查,看看类型本身是否可为null
,并抛出一个异常,如果这是你需要的行为。@Servy:哦,当然。我只是想向Chad指出其中一个警告,因为我们不一定知道他预期用途的全部范围;我不想让他后来感到惊讶。公共静态字符串GetTypeName(此类型)
用于扩展方法!
GetNullableUnderlyingTypeIfNullable(typeof(DateTime?)).Name