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

adr*_*rin 80 c# enums nullable

我如何检查Type是否是C#中可以为空的枚举

Type t = GetMyType();
bool isEnum = t.IsEnum; //Type member
bool isNullableEnum = t.IsNullableEnum(); How to implement this extension method?
Run Code Online (Sandbox Code Playgroud)

Luk*_*keH 159

public static bool IsNullableEnum(this Type t)
{
    Type u = Nullable.GetUnderlyingType(t);
    return (u != null) && u.IsEnum;
}
Run Code Online (Sandbox Code Playgroud)


Jon*_*eet 42

编辑:我将把这个答案留下来,因为它会起作用,它会演示一些读者可能不知道的电话.然而,卢克的答案肯定更好 - 去投票吧:)

你可以做:

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

  • 哇,很奇怪.Jon的答案不是被接受的答案;) (6认同)
  • @Marc:我不知道它如何为*来电者*带来任何可能性 - 但卢克的方式肯定比我的好. (2认同)

Big*_*jim 11

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

Nullable.GetUnderlyingType(t)?.IsEnum == true
Run Code Online (Sandbox Code Playgroud)

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