C#枚举从值列表中验证

时间:2015-02-16 19:28:35

标签: c# enums

我在某个地方(无法找到它)看到你可以检查枚举项中是否存在枚举值,该枚举项具有特定的项目列表。防爆。下面 - "可用= doc | xls | CSV"

但以下代码似乎不起作用。我希望结果是= xls而不是doc,因为它在"可用"的列表中。值。

有人可以帮忙吗?

提前致谢!

尼基

按钮代码:

protected void btnTest01_Click(object sender, EventArgs e)
{
    TestEnum01 result1 = TestEnum01.xls;
    TestEnum02 result2 = TestEnum02.xls;
    TestEnum03 result3 = TestEnum03.xls;

    if (result1 != TestEnum01.Available)
    {
        result1 = TestEnum01.doc;
    }

    if (result2 != TestEnum02.Available)
    {
        result2 = TestEnum02.doc;
    }

    if (result3 != TestEnum03.Available)
    {
        result3 = TestEnum03.doc;
    }

    this.txtTest01_Results.Text =
        String.Format("01: Result = {0}, Available = {1}\r\n\r\n02: Result = {2}, Available = {3}\r\n\r\n03: Result = {4}, Available = {5}",
        result1.ToString(), TestEnum01.Available,
        result2.ToString(), TestEnum02.Available,
        result3.ToString(), TestEnum03.Available);
    }

ENUMS

public enum TestEnum01
{
    doc = 1,
    txt = 2,
    xls = 4,
    csv = 8,
    unknown = 5,
    Available = doc | xls | csv
}

public enum TestEnum02
{
    doc,
    txt,
    xls,
    csv,
    unknown,
    Available = doc | xls | csv
}

public enum TestEnum03
{
    doc,
    txt,
    xls,
    csv,
    unknown,
    Available = TestEnum03.doc | TestEnum03.xls | TestEnum03.csv
}

结果:

01: Result = doc, Available = Available
02: Result = doc, Available = csv
03: Result = doc, Available = csv

1 个答案:

答案 0 :(得分:3)

您必须使用FlagsAttribute

[Flags]
public enum TestEnum01
{
    doc = 1,
    txt = 2,
    xls = 4,
    csv = 8,
    unknown = 5,
    Available = doc | xls | csv
}

然后测试它:

TestEnum01 test = TestEnum01.doc | TestEnum01.txt;
bool isDoc = (test & TestEnum01.doc) == TestEnum01.doc;

请注意,在您的示例中,您将遇到unknown值的问题,因为二进制明智,1 | 4 = 5 ......这意味着doc和xls产生未知......为了避免这种问题,我更喜欢使用直接位移符号:

[Flags]
public enum TestEnum01
{
    unknown = 0,
    doc = 1 << 0,
    txt = 1 << 1,
    xls = 1 << 2,
    csv = 1 << 3,
    Available = doc | xls | csv
}

如果您只想测试特定标志,可以使用HasFlag()方法

TestEnum01 test = TestEnum01.doc | TestEnum01.txt;
bool isDoc = test.HasFlag(TestEnum01.doc);