2010-04-27 53 views
63

我如何檢查如果一個類型是在C#中爲空的枚舉 像察看類型實例在C#中爲空的枚舉

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

回答

128
public static bool IsNullableEnum(this Type t) 
{ 
    Type u = Nullable.GetUnderlyingType(t); 
    return (u != null) && u.IsEnum; 
} 
38

編輯:我要離開這個答案了,因爲它會工作,它展示了一些讀者可能不知道的電話。然而,Luke's answer絕對是更好的 - 去給予好評吧:)

你可以這樣做:

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

我想我會做到這一點盧克的方式;來電者較不復雜。 – 2010-04-27 16:44:10

+1

@Marc:我不明白它是如何使*調用者產生任何可能性 - 但盧克的方式肯定比我的更好。 – 2010-04-27 16:45:45

+0

是的,絕對保留以備將來參考 – adrin 2010-04-27 16:50:04

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

我離開了IsEnum選中您已經作出,因爲這使得這種方法更普遍。

5

由於從C#6.0中接受的答案可以重構爲

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

的==真正需要轉換布爾?布爾