2016-03-09 27 views
13

優化枚舉分配我有這個枚舉如何在C#

enum NetopScriptGeneratingCases 
{ 
    AddLogMessages, 
    AddLogErrors, 
    AddLogJournal, 
    AllLog = AddLogMessages | AddLogErrors | AddLogJournal, 
    DoNothing 
} 

而且有3個複選框,以便根據哪些是檢查我不得不產生可能的情況做一些工作UI。

NetopScriptGeneratingCases netopScriptGeneratingCases = NetopScriptGeneratingCases.DoNothing; 

if (checkBoxAddAuditLog.Checked) 
{ 
    netopScriptGeneratingCases = NetopScriptGeneratingCases.AddLogJournal; 
} 
else if (checkBoxAddErrorLog.Checked) 
{ 
    netopScriptGeneratingCases = NetopScriptGeneratingCases.AddLogErrors; 
} 
else if (checkBoxAddLogMessages.Checked) 
{ 
    netopScriptGeneratingCases = NetopScriptGeneratingCases.AddLogMessages; 
} 
else if (checkBoxAddAuditLog.Checked || checkBoxAddErrorLog.Checked) 
{ 
    netopScriptGeneratingCases = NetopScriptGeneratingCases.AddLogJournal | NetopScriptGeneratingCases.AddLogErrors; 
} 
else if (checkBoxAddAuditLog.Checked || checkBoxAddLogMessages.Checked) 
{ 
    netopScriptGeneratingCases = NetopScriptGeneratingCases.AddLogJournal | NetopScriptGeneratingCases.AddLogMessages; 
} 
else if (checkBoxAddErrorLog.Checked || checkBoxAddLogMessages.Checked) 
{ 
    netopScriptGeneratingCases = NetopScriptGeneratingCases.AddLogErrors | NetopScriptGeneratingCases.AddLogMessages; 
} 
else if (checkBoxAddErrorLog.Checked || checkBoxAddLogMessages.Checked || checkBoxAddAuditLog.Checked) 
{ 
    netopScriptGeneratingCases = NetopScriptGeneratingCases.AddLogErrors | NetopScriptGeneratingCases.AddLogMessages | NetopScriptGeneratingCases.AddLogJournal; 
} 


var modifiedFiles = NetopScriptGenerator.GenerateNetopScript(netopScriptGeneratingCases, netopFiles); 

但我不確定這段代碼是否正確......是否有其他方法可以做到這一點?

+9

如果你要使用你的'enum'爲一組標誌,你通過or'ing他們在一起創建'AllLog',然後你需要給他們賦值爲2的值。那就是你應該將第一個設置爲1,然後是2,然後是4,並且'DoNothing'應該被設置爲0. – juharr

+3

我認爲寫代碼的方式是有缺陷的,因爲第一次檢查會吞下很多其他檢查;你應該嘗試最具體,讓更一般的情況下結束。 –

回答

18

我會採取什麼Chris suggest in his answer,並指定你的變量,像這樣:

NetopScriptGeneratingCases netopScriptGeneratingCases = NetopScriptGeneratingCases.DoNothing; 

if (checkBoxAddAuditLog.Checked) 
{ 
    netopScriptGeneratingCases |= NetopScriptGeneratingCases.AddLogJournal; 
} 
if (checkBoxAddErrorLog.Checked) 
{ 
    netopScriptGeneratingCases |= NetopScriptGeneratingCases.AddLogErrors; 
} 
if (checkBoxAddLogMessages.Checked) 
{ 
    netopScriptGeneratingCases |= NetopScriptGeneratingCases.AddLogMessages; 
} 
21

正如在評論中提到的,編譯器默認會給枚舉一個遞增的整數值,它不適合用作位標誌。嘗試修改您的定義如下:

[Flags] 
enum NetopScriptGeneratingCases 
{ 
     DoNothing = 0, 
     AddLogMessages = 1<<0, 
     AddLogErrors = 1<<1, 
     AddLogJournal = 1<<2, 
     AllLog = AddLogMessages | AddLogErrors | AddLogJournal 
} 
+0

附錄:做相反的事情,所以檢查哪些是設置的,你和該域(例如'if(values&Enum.AddLogMessages)')或1s的位掩碼來獲取它們。 – edmz