简体   繁体   中英

C# Enum validate from list of values

I saw somewhere (cannot find it anymore) that you can check the existence of an enum value from an enum item with a specific list of items. Ex. below - "Available = doc | xls | csv"

But the following code does not seem to work. I'm expecting the results to be = xls instead of doc, since it is in the list of "Available" values.

Can someone please help?

Thanks in advance!

Niki

Button Code:

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
}

RESULTS:

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

You have to use the FlagsAttribute :

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

Then to test it :

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

Note that in your example, you will have a problem with unknown value, since binary wise, 1 | 4 = 5 ... And that means doc and xls produces unknown... To avoid this kind of problems, I prefer to use a direct bit-shift notation :

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

If you just want to test for a particular flag, you can just use the HasFlag() method

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM