typeof(DateTime?).Name == Nullable`1

Cha*_*sch 7 .net c# system.reflection

在.Net中使用Reflection typeof(DateTime?).Name返回"Nullable`1".

有没有办法将实际类型作为字符串返回.(在本例中为"DateTime"或"System.DateTime")

我明白的DateTime?Nullable<DateTime>.除此之外,我只是在寻找可空类型的类型.

Chr*_*air 14

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;
}
Run Code Online (Sandbox Code Playgroud)

用法:

Console.WriteLine(GetTypeName(typeof(DateTime?))); //outputs "DateTime"
Console.WriteLine(GetTypeName(typeof(DateTime))); //outputs "DateTime"
Run Code Online (Sandbox Code Playgroud)

编辑:我怀疑你也可能在类型上使用其他机制,在这种情况下,您可以稍微修改它以获取基础类型或使用现有类型,如果它不可为空:

public static Type GetNullableUnderlyingTypeOrTypeIfNonNullable(this Type possiblyNullableType)
{
    var nullableType = Nullable.GetUnderlyingType(possiblyNullableType);

    bool isNullableType = nullableType != null;

    if (isNullableType)
        return nullableType;
    else
        return possiblyNullableType;
}
Run Code Online (Sandbox Code Playgroud)

对于一种方法来说,这是一个可怕的名字,但我不够聪明,想出一个方法(如果有人建议更好的话,我会很乐意改变它!)

然后作为扩展方法,您的用法可能如下:

public static string GetTypeName(this Type type)
{
    return type.GetNullableUnderlyingTypeOrTypeIfNonNullable().Name;
}
Run Code Online (Sandbox Code Playgroud)

要么

typeof(DateTime?).GetNullableUnderlyingTypeOrTypeIfNonNullable().Name
Run Code Online (Sandbox Code Playgroud)

  • `public static string GetTypeName(this Type type)`for extension method! (2认同)

小智 6

Chris Sinclair代码可以工作,但我将其重写得更加简洁。

public static Type GetNullableUnderlyingTypeIfNullable(Type possiblyNullableType)
    {
        return Nullable.GetUnderlyingType(possiblyNullableType) ?? possiblyNullableType;
    }
Run Code Online (Sandbox Code Playgroud)

然后使用它:

GetNullableUnderlyingTypeIfNullable(typeof(DateTime?)).Name
Run Code Online (Sandbox Code Playgroud)


Cha*_*sch 5

正如Patryk指出的那样:

typeof(DateTime?).GetGenericArguments()[0].Name