在“标记的枚举”中将所有值“或”的最巧妙方法? [英] Neatest way to 'OR' all values in a Flagged Enum?

查看:75
本文介绍了在“标记的枚举”中将所有值“或”的最巧妙方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出枚举

[Flags]
public enum mytest
{
    a = 1,
    b = 2,
    c = 4
}

我想出了两种方法来表示单个变量中的所有值:

I've come up with two ways to represent all values in a single variable:

    var OR1 = (mytest)Enum.GetNames(typeof(mytest)).Sum(a => (int)Enum.Parse(typeof(mytest), a));
    var OR2 = (mytest)(typeof(mytest).GetEnumValues() as mytest[]).Sum(a => (int)a);

现在,尽管它们都起作用,有没有更整洁的方法?可能是我缺少的.NET方法?

Now, although they both work, is there a neater way? Possibly a .NET method I'm missing?

编辑:为了澄清起见,我需要函数是动态的-我不想通过指定每个函数来计算它枚举值。

For clarification, I need the function to be dynamic - I don't want to calculate it by specifying every single enum value.

推荐答案

如果有 All 成员,只需直接提供即可:

If it makes sense to have an All member, just provide it directly:

[Flags]
public enum mytest
{
    a = 1,
    b = 2,
    c = 4,
    All = 7
}

不过,更惯用的写法可能是:

Though, a more idiomatic way to write these could be:

[Flags]
public enum MyTest
{
    A = 1,
    B = 1 << 0x01,
    C = 1 << 0x02,
    All = A | B | C
}

这显示枚举值的逻辑级数,并在 All 的情况下,可以轻松添加其他成员。

This shows the logical progression of the enum values, and in the All case, makes it easy to add another member.

这篇关于在“标记的枚举”中将所有值“或”的最巧妙方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆