2012-11-16 29 views
0

借用此問題的代碼How do I check if more than one enum flag is set?我試圖實現執行此測試的通用擴展。檢查是否在通用擴展中設置了多個標誌

我的第一次嘗試是以下。

public static bool ExactlyOneFlagSet(this Enum enumValue) 
{ 
    return !((enumValue & (enumValue - 1)) != 0); 
} 

這就造成了

操作 ' - ' 不能應用於類型 'System.Enum' 和 '廉政'

OK有意義的操作數,所以我想我會嘗試這樣的事情

public static bool ExactlyOneFlagSet<T>(this T enumValue) where T : struct, IConvertible 
{ 
    return !(((int)enumValue & ((int)enumValue - 1)) != 0); 
} 

這就造成了

不能鍵入「T」轉換爲「廉政」

閱讀有關此行爲,但隨後如何在地球上可以在此擴展方法實施之後也是情理之中。任何人都可以幫助嗎?

回答

2

既然你contrain T實現IConvertible,你可以簡單地調用ToInt32

public static bool ExactlyOneFlagSet<T>(this T enumValue) 
    where T : struct, IConvertible 
{ 
    int v = enumValue.ToInt32(null); 
    return (v & (v - 1)) == 0; 
} 
+0

看起來你,你需要提供一個文化! int v = enumValue.ToInt32(System.Threading.Thread.CurrentThread.CurrentCulture);我錯了嗎?否則看起來很美,現在測試 –

相關問題