如何在C#中优化枚举赋值

时间:2016-03-09 12:24:14

标签: c# enums flags

我有这个枚举

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);

但我不确定这段代码是否正确......还有其他方法吗?

2 个答案:

答案 0 :(得分:21)

如注释中所述,编译器默认情况下会为枚举提供递增的整数值,这不适合用作bitflags。尝试按如下方式修改您的定义:

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

答案 1 :(得分: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;
}