简体   繁体   English

通用枚举标志解析器

[英]Generic Enum Flag Parser

I have an array of string values that I would like to have set flags on a Flags Enum object. 我有一个字符串值数组,希望在Flags Enum对象上设置标志。 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. 我有几种这样的方法,并且正在寻找一种更通用的方式来传递Flags枚举的类型,而不必为每种Flags Enum类型重复该方法。 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. 我一直在寻找一种更通用的方式来做同样的事情,同时能够使用任何Flags Enum类型。

Enum.Parse can already combine multiple flags. Enum.Parse已经可以合并多个标志。 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 (,). value参数包含枚举成员的基础值或命名常量的字符串表示形式,或用逗号(,)分隔的命名常量列表。 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. 如果value是一个列表,则返回值是指定名称的值与按位或运算的组合。

So you could do it like this: 因此,您可以这样做:

public static T ParseFlagsEnum<T>(string[] values)
{
  return (T)Enum.Parse(typeof(T), string.Join(",", values));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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