Domanda

I have an array of string values that I would like to have set flags on a Flags Enum object. I have several of these and was looking for a more generic way to pass in the type of the Flags enum and not have to duplicate the method for each Flags Enum type. This is what I have currently:

    public static MyFlagsEnum ParseFlagsEnum(string[] values)
    {
        MyFlagsEnum flags = new MyFlagsEnum();
        foreach (var flag in values)
        {
            flags |= (MyFlagsEnum)Enum.Parse(typeof(MyFlagsEnum), flag);
        }

        return flags;
    }

I was looking for a more generic way of doing the same thing, while being able to use any Flags Enum type.

È stato utile?

Soluzione

Enum.Parse can already combine multiple flags. Quoting from the documentation:

Remarks

The value parameter contains the string representation of an enumeration member's underlying value or named constant, or a list of named constants delimited by commas (,). One or more blank spaces can precede or follow each value, name, or comma in value. If value is a list, the return value is the value of the specified names combined with a bitwise OR operation.

So you could do it like this:

public static T ParseFlagsEnum<T>(string[] values)
{
  return (T)Enum.Parse(typeof(T), string.Join(",", values));
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top