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

标签 c# .net system.reflection

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

有什么方法可以将实际类型作为字符串返回。 (在本例中为“DateTime”或“System.DateTime”)

我明白 DateTime?Nullable<DateTime> .这不是重点,我只是在寻找可空类型的类型。

最佳答案

有一个 Nullable.GetUnderlyingType在这种情况下可以帮助您的方法。您可能最终会想要创建自己的实用方法,因为(我假设)您将同时使用可为 null 和不可为 null 的类型:

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

关于c# - typeof(DateTime?).Name == Nullable`1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20659801/

相关文章:

c# - 根据特定比较器获取两个列表中的对象

asp.net - JavaScript 触发 - vb.net api 调用的反射?

c# - 如何使用一个动态生成的对象作为CodeEffects生成器的数据源

c# - 在 ListView 中提取和吐出数据库项目

c# - 登录 Microsoft AD 后 Request.IsAuthenticated 始终为 false

.net - 当路径\文件名超过 260 个字符时,在 PowerShell 中获取/设置文件属性

c# - 当鼠标进入 WPF ComboBox 下拉列表时防止滚动

c# - 如何获取类型中的方法

c# - 为什么 javascript 有函数而 C# 有方法?

c# - LINQ to xml - 如何选择特定节点?