如何检查 C# 中的 Type 是否为可空枚举 类似的东西
Type t = GetMyType();
bool isEnum = t.IsEnum; //Type member
bool isNullableEnum = t.IsNullableEnum(); How to implement this extension method?
public static bool IsNullableEnum(this Type t)
{
Type u = Nullable.GetUnderlyingType(t);
return u != null && u.IsEnum;
}
编辑:我将保留这个答案,因为它会起作用,并且它演示了读者可能不知道的一些调用。然而,卢克的回答肯定更好 - 投票吧:)
你可以这样做:
public static bool IsNullableEnum(this Type t)
{
return t.IsGenericType &&
t.GetGenericTypeDefinition() == typeof(Nullable<>) &&
t.GetGenericArguments()[0].IsEnum;
}
从 C# 6.0 开始,接受的答案可以重构为
Nullable.GetUnderlyingType(t)?.IsEnum == true
转换 bool 需要 == true 吗?布尔
public static bool IsNullable(this Type type)
{
return type.IsClass
|| (type.IsGeneric && type.GetGenericTypeDefinition == typeof(Nullable<>));
}
我遗漏了您已经进行的
IsEnum
检查,因为这使得该方法更加通用。