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)
Big*_*jim 11
从C#6.0开始,接受的答案可以重构为
Nullable.GetUnderlyingType(t)?.IsEnum == true
Run Code Online (Sandbox Code Playgroud)
转换bool需要== true吗?布尔