【问题标题】:typeof(DateTime?).Name == Nullable`1typeof(DateTime?).Name == Nullable`1
【发布时间】:2017-09-06 18:08:36
【问题描述】:

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

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

我知道DateTime?Nullable<DateTime>。除此之外,我只是在寻找可空类型的类型。

【问题讨论】:

  • 实际类型为Nullable<DateTime>
  • 去掉问号。
  • 请记住,作为测试,这很好,删除代码中的问号可能会破坏一些东西。
  • 如果你想通过反射选择泛型类型名称,在这种情况下你必须使用GetGenericArguments()[0]如果它实际上每次都是泛型类型,如果没有,您必须检查它。

标签: c# .net system.reflection


【解决方案1】:

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

【讨论】:

  • public static string GetTypeName(this Type type) 用于扩展方法!
【解决方案2】:

Patryk 指出:

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

【讨论】:

  • 唯一的问题是,如果在实践中,这是获取类型的通用方法,这也会为List<int>等类型提取泛型类型。
  • @ChrisSinclair 可以简单地添加检查以查看类型本身是否为 Nullable 并抛出异常,如果这是您需要的行为。
  • @Servy:当然可以。我只是想向乍得指出其中一个警告,因为我们不一定知道他预期用途的全部范围;不想让他后来在路上感到惊讶。
【解决方案3】:

Chris Sinclair 代码有效,但我将其重写得更简洁。

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

然后使用它:

GetNullableUnderlyingTypeIfNullable(typeof(DateTime?)).Name

【讨论】:

    猜你喜欢
    • 2015-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-20
    • 2011-05-31
    • 1970-01-01
    • 2014-07-01
    • 1970-01-01
    相关资源
    最近更新 更多