如果我有一个持有一个标志枚举的变量,我可以以某种方式迭代该特定变量中的位值吗? 或者我必须使用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?
最满意答案
static IEnumerable<Enum> GetFlags(Enum input) { foreach (Enum value in Enum.GetValues(input.GetType())) if (input.HasFlag(value)) yield return value; }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; } } }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.)
更多推荐
发布评论