迭代中旗枚举值? [英] Iterate over values in Flags Enum?

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

问题描述

如果我有一个变量抱着一个标志枚举,我可以采用某种遍历位值在特定的变量?还是我用Enum.GetValues​​来遍历整个枚举,检查哪些设置?

If I have a variable holding a flags enum, can I somehow iterate over the 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?

推荐答案

说回这几年后,随着更多的经验,我的唯一的单位值最终的答案,从最低位移动到最高位,是杰夫·梅尔卡多的内在程序的轻微变种:

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.)

这篇关于迭代中旗枚举值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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