检查 Type 实例是否是 C# 中的可空枚举

问题描述 投票:0回答:5

如何检查 C# 中的 Type 是否为可空枚举 类似的东西

Type t = GetMyType();
bool isEnum = t.IsEnum; //Type member
bool isNullableEnum = t.IsNullableEnum(); How to implement this extension method?
c# enums nullable
5个回答
204
投票
public static bool IsNullableEnum(this Type t)
{
    Type u = Nullable.GetUnderlyingType(t);
    return u != null && u.IsEnum;
}

46
投票

编辑:我将保留这个答案,因为它会起作用,并且它演示了读者可能不知道的一些调用。然而,卢克的回答肯定更好 - 投票吧:)

你可以这样做:

public static bool IsNullableEnum(this Type t)
{
    return t.IsGenericType &&
           t.GetGenericTypeDefinition() == typeof(Nullable<>) &&
           t.GetGenericArguments()[0].IsEnum;
}

32
投票

从 C# 6.0 开始,接受的答案可以重构为

Nullable.GetUnderlyingType(t)?.IsEnum == true

转换 bool 需要 == true 吗?布尔


1
投票
public static bool IsNullable(this Type type)
{
    return type.IsClass
        || (type.IsGeneric && type.GetGenericTypeDefinition == typeof(Nullable<>));
}

我遗漏了您已经进行的

IsEnum
检查,因为这使得该方法更加通用。


© www.soinside.com 2019 - 2024. All rights reserved.