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

查看:33
本文介绍了typeof(DateTime?).Name ==可空`1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using Reflection in .Net typeof(DateTime?).Name returns "Nullable`1".

有什么方法可以将实际类型作为字符串返回.(在这种情况下为"DateTime"或"System.DateTime")

Is there any way to return the actual type as a string. (in this case "DateTime" or "System.DateTime")

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

I understand that DateTime? is 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. 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;
}

用法:

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


我怀疑您可能还在该类型上使用其他机制,在这种情况下,您可以对其稍加修改以获取基础类型,或者如果它不可为空,则使用现有类型:


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;
}

typeof(DateTime?).GetNullableUnderlyingTypeOrTypeIfNonNullable().Name

这篇关于typeof(DateTime?).Name ==可空`1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆