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

∥☆過路亽.° 提交于 2019-12-05 05:08:52

There's a Nullable.GetUnderlyingType method which can help you in this case. 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

As Pointed out by Patryk:

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

user7414009

Chris Sinclair code works but I rewrote it more concise.

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

And then use it:

GetNullableUnderlyingTypeIfNullable(typeof(DateTime?)).Name
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!