简体   繁体   中英

C# Flags parsing

I have wrote enum:

[Flags]
public enum BundleOS {
    Win32 = 0,
    Win64 = 1,
    Mac = 2
}

I need parse it from string, and write to string. Sample of string: "Win32|Win64" . Next code returns invalid result:

BundleOS os;
Boolean result = TryParse<BundleOS>("Win32|Win64", out os);

In result variable I got the false value. But I need true , and os value must to have the BundleOS.Win32|BundleOS.Win64 value.


If I do such operation:

String x = (BundleOS.Win32|BundleOS.Win64).ToString();

I need get such value: "Win32|Win64" , but I get "Win64" .

Is exists a simple solution of these problems?

Your problem is that your performing a bitwise operation and Win32 equals 0.
So Win64 OR Win32 is actually Win64 OR 0 which returns Win64 .

You can set your enum like this:

[Flags]
public enum BundleOS 
{
     Win32 = 1,
     Win64 = 2,
     Mac = 4
}

On a side note: I'll also point out a very good question that was asked earlier this week on how to define flag enums .

In addition to the answer given by @Blachshma regarding your particular flags, if you want to take the string form of "Win32|Win64" and turn it into an actual instance of your enum, you've got a bit more work cut out.

First you'll simply need to split() the string by the '"|"' in order to get the individual values.

Then you can use Enum.GetNames() and Enum.GetValues() to get a list of the names and values for elements in your original enum. You can then loop through the split components, and find the matching entry (and its value) from your original enum.

Try this to parse your flags string. I havn't tested but it should get you started:

BundleOS flags = "Win32|Win64"
                    .Split('|')
                    .Select(s => (BundleOS)Enum.Parse(typeof(BundleOs), s))
                   .Aggregate((f, i) => f|i);

In addition to Blachshma's answer, the MSDN documentation for the FlagsAttribute actually explains very succinctly in the "Guidelines for FlagsAttribute and Enum" section:

Define enumeration constants in powers of two, that is, 1, 2, 4, 8, and so on. This means the individual flags in combined enumeration constants do not overlap.

Use None as the name of the flag enumerated constant whose value is zero. You cannot use the None enumerated constant in a bitwise AND operation to test for a flag because the result is always zero. However, you can perform a logical, not a bitwise, comparison between the numeric value and the None enumerated constant to determine whether any bits in the numeric value are set.

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