如何迭代具有标志的 Enum 的值? [英] How to iterate over values of an Enum having flags?

查看:22
本文介绍了如何迭代具有标志的 Enum 的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个保存标志枚举的变量,我可以以某种方式迭代该特定变量中的单个位值吗?或者我是否必须使用 Enum.GetValues 来遍历整个枚举并检查设置了哪些?

If I have a variable holding a flags enum, can I somehow iterate over the single-bit values in that specific variable? Or do I have to use Enum.GetValues to iterate over the entire enum and check which ones are set?

推荐答案

几年后回到这个问题,有了更多的经验,我的最终答案只针对一位值,从最低位到最高位,是杰夫·梅尔卡多 (Jeff Mercado) 内心常规的轻微变体:

Coming back at this a few years later, with a bit more experience, my ultimate answer for single-bit values only, moving from lowest bit to highest bit, is a slight variant of Jeff Mercado's inner routine:

public static IEnumerable<Enum> GetUniqueFlags(this Enum flags)
{
    ulong flag = 1;
    foreach (var value in Enum.GetValues(flags.GetType()).Cast<Enum>())
    {
        ulong bits = Convert.ToUInt64(value);
        while (flag < bits)
        {
            flag <<= 1;
        }

        if (flag == bits && flags.HasFlag(value))
        {
            yield return value;
        }
    }
}

它似乎有效,尽管我几年前反对,但我在这里使用 HasFlag,因为它比使用按位比较要清晰得多,而且速度差异对于我将要做的任何事情都无关紧要.(从那时起,他们完全有可能提高了 HasFlags 的速度,据我所知……我还没有测试过.)

It seems to work, and despite my objections of some years ago, I use HasFlag here, since it's far more legible than using bitwise comparisons and the speed difference is insignificant for anything I'll be doing. (It's entirely possible they've improved the speed of HasFlags since then anyway, for all I know...I haven't tested.)

这篇关于如何迭代具有标志的 Enum 的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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