简体   繁体   English

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

[英]typeof(DateTime?).Name == Nullable`1

Using Reflection in .Net typeof(DateTime?).Name returns "Nullable`1". 在.Net typeof(DateTime?).Name使用Reflection typeof(DateTime?).Name返回“Nullable`1”。

Is there any way to return the actual type as a string. 有没有办法将实际类型作为字符串返回。 (in this case "DateTime" or "System.DateTime") (在本例中为“DateTime”或“System.DateTime”)

I understand that DateTime? 我明白DateTime? is Nullable<DateTime> . Nullable<DateTime> That's besides the point, I am just looking for the type of the nullable type. 除此之外,我只是在寻找可空类型的类型。

There's a Nullable.GetUnderlyingType method which can help you in this case. 在这种情况下,有一个Nullable.GetUnderlyingType方法可以帮助您。 Likely you'll end up wanting to make your own utility method because (I'm assuming) you'll be using both nullable and non-nullable types: 可能你最终想要制作自己的实用工具方法,因为(我假设)你将使用可空和非可空类型:

public static string GetTypeName(Type type)
{
    var nullableType = Nullable.GetUnderlyingType(type);

    bool isNullableType = nullableType != null;

    if (isNullableType)
        return nullableType.Name;
    else
        return type.Name;
}

Usage: 用法:

Console.WriteLine(GetTypeName(typeof(DateTime?))); //outputs "DateTime"
Console.WriteLine(GetTypeName(typeof(DateTime))); //outputs "DateTime"

EDIT: I suspect you may also be using other mechanisms on the type, in which case you can slightly modify this to get the underlying type or use the existing type if it's non-nullable: 编辑:我怀疑你也可能在类型上使用其他机制,在这种情况下,您可以稍微修改它以获取基础类型或使用现有类型,如果它不可为空:

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

    bool isNullableType = nullableType != null;

    if (isNullableType)
        return nullableType;
    else
        return possiblyNullableType;
}

And that is a terrible name for a method, but I'm not clever enough to come up with one (I'll be happy to change it if someone suggests a better one!) 对于一种方法来说,这是一个可怕的名字,但我不够聪明,想出一个方法(如果有人建议更好的话,我会很乐意改变它!)

Then as an extension method, your usage might be like: 然后作为扩展方法,您的用法可能如下:

public static string GetTypeName(this Type type)
{
    return type.GetNullableUnderlyingTypeOrTypeIfNonNullable().Name;
}

or 要么

typeof(DateTime?).GetNullableUnderlyingTypeOrTypeIfNonNullable().Name

正如Patryk指出的那样:

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

Chris Sinclair code works but I rewrote it more concise. Chris Sinclair代码可以工作,但我更简洁地重写了它。

public static Type GetNullableUnderlyingTypeIfNullable(Type possiblyNullableType)
    {
        return Nullable.GetUnderlyingType(possiblyNullableType) ?? possiblyNullableType;
    }

And then use it: 然后使用它:

GetNullableUnderlyingTypeIfNullable(typeof(DateTime?)).Name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM