【发布时间】:2011-02-12 23:05:53
【问题描述】:
如何在 C# 中检查类型是否为可为空的枚举 像
Type t = GetMyType();
bool isEnum = t.IsEnum; //Type member
bool isNullableEnum = t.IsNullableEnum(); How to implement this extension method?
【问题讨论】:
如何在 C# 中检查类型是否为可为空的枚举 像
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;
}
【讨论】:
编辑:我将保留这个答案,因为它会起作用,它展示了一些读者可能不知道的电话。但是,Luke's answer 绝对更好 - 去投票吧:)
你可以这样做:
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
需要== true 来转换bool?布尔
【讨论】:
public static bool IsNullable(this Type type)
{
return type.IsClass
|| (type.IsGeneric && type.GetGenericTypeDefinition == typeof(Nullable<>));
}
我省略了您已经进行的IsEnum 检查,因为这使此方法更通用。
【讨论】: