找到标志枚举长度的有效方法?

Val*_*yev 7 c# enums flags

考虑一下:

[Flags]
enum Colors
{
    Red=1,
    Green=2,
    Blue=4
}

Colors myColor=Colors.Red|Colors.Blue;
Run Code Online (Sandbox Code Playgroud)

目前,我的做法如下:

int length=myColors.ToString().Split(new char[]{','}).Length;
Run Code Online (Sandbox Code Playgroud)

但我希望有一种更有效的方法来查找长度,可能基于bitset操作.

如果可能,请说明解决方案的原因和方式.

此外,如果这是重复,请指出它,我将删除此问题.关于SO我能找到的唯一类似的问题关注的是找到所有可能的Colors枚举组合的长度,而不是myColors变量的长度.

更新:我仔细地对每个解决方案进行了基准测试(每个解决方案1 ​​000 000次),结果如下:

  1. Stevo3000 - 8ms
  2. MattEvans - 10ms
  3. Silky - 34ms
  4. 卢克 - 1757ms
  5. Guffa - 4226ms
  6. Tomas Levesque - 32810ms

Stevo3000是一个明显的赢家(Matt Evans持有银牌).

非常感谢您的帮助.

更新2:此解决方案运行速度更快:100 000次迭代时为41 ms(比Stevo3000快约40倍(32位操作系统))

UInt32 v = (UInt32)co;
v = v - ((v >> 1) & 0x55555555); 
v = (v & 0x33333333) + ((v >> 2) & 0x33333333); 
UInt32 count = ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; 
Run Code Online (Sandbox Code Playgroud)

ste*_*ell 10

下面的代码将为您提供为给定数量的任何类型设置的位数,其大小从byte到long不等.

public static int GetSetBitCount(long lValue)
{
  int iCount = 0;

  //Loop the value while there are still bits
  while (lValue != 0)
  {
    //Remove the end bit
    lValue = lValue & (lValue - 1);

    //Increment the count
    iCount++;
  }

  //Return the count
  return iCount;
}
Run Code Online (Sandbox Code Playgroud)

这段代码非常有效,因为它只针对每个位迭代一次,而不是像其他示例那样针对每个可能的位迭代一次.