微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – typeof(DateTime?).Name == Nullable`1

在.Net typeof(DateTime?)中使用Reflection.名称返回“Nullable`1”.

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

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

解决方法

在这种情况下,有一个 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

原文地址:https://www.jb51.cc/csharp/98872.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐