在我的生活中,我不记得如何设置,删除,切换或测试位域中的位。要么我不确定,要么我把它们弄混了,因为我很少需要它们。所以有一个“bit-cheat-sheet”会很好。

例如:

flags = flags | FlagsEnum.Bit4;  // Set bit 4.

or

if ((flags & FlagsEnum.Bit4)) == FlagsEnum.Bit4) // Is there a less verbose way?

你能给出所有其他常见操作的例子吗,最好是在c#语法中使用[Flags]枚举?


当前回答

c++操作为:& | ^ ~(用于和,或,xor,而不是位操作)。还有>>和<<,它们是位移位操作。

因此,要测试是否在标志中设置了位,你可以使用: 如果(flags & 8) //测试位4已设置

其他回答

习惯用法是使用按位或等于操作符来设置位:

flags |= 0x04;

为了澄清一点,这个习语是按位使用,并带否定:

flags &= ~0x04;

有时你有一个偏移量来标识你的位,然后习惯用法是将这些偏移量与左移结合使用:

flags |= 1 << offset;
flags &= ~(1 << offset);

为了获得最佳性能和零垃圾,请使用以下代码:

using System;
using T = MyNamespace.MyFlags;

namespace MyNamespace
{
    [Flags]
    public enum MyFlags
    {
        None = 0,
        Flag1 = 1,
        Flag2 = 2
    }

    static class MyFlagsEx
    {
        public static bool Has(this T type, T value)
        {
            return (type & value) == value;
        }

        public static bool Is(this T type, T value)
        {
            return type == value;
        }

        public static T Add(this T type, T value)
        {
            return type | value;
        }

        public static T Remove(this T type, T value)
        {
            return type & ~value;
        }
    }
}

这是受到在Delphi中使用set作为索引器的启发,在很久以前:

/// Example of using a Boolean indexed property
/// to manipulate a [Flags] enum:

public class BindingFlagsIndexer
{
  BindingFlags flags = BindingFlags.Default;

  public BindingFlagsIndexer()
  {
  }

  public BindingFlagsIndexer( BindingFlags value )
  {
     this.flags = value;
  }

  public bool this[BindingFlags index]
  {
    get
    {
      return (this.flags & index) == index;
    }
    set( bool value )
    {
      if( value )
        this.flags |= index;
      else
        this.flags &= ~index;
    }
  }

  public BindingFlags Value 
  {
    get
    { 
      return flags;
    } 
    set( BindingFlags value ) 
    {
      this.flags = value;
    }
  }

  public static implicit operator BindingFlags( BindingFlagsIndexer src )
  {
     return src != null ? src.Value : BindingFlags.Default;
  }

  public static implicit operator BindingFlagsIndexer( BindingFlags src )
  {
     return new BindingFlagsIndexer( src );
  }

}

public static class Class1
{
  public static void Example()
  {
    BindingFlagsIndexer myFlags = new BindingFlagsIndexer();

    // Sets the flag(s) passed as the indexer:

    myFlags[BindingFlags.ExactBinding] = true;

    // Indexer can specify multiple flags at once:

    myFlags[BindingFlags.Instance | BindingFlags.Static] = true;

    // Get boolean indicating if specified flag(s) are set:

    bool flatten = myFlags[BindingFlags.FlattenHierarchy];

    // use | to test if multiple flags are set:

    bool isProtected = ! myFlags[BindingFlags.Public | BindingFlags.NonPublic];

  }
}

在。net 4中,你现在可以这样写:

flags.HasFlag(FlagsEnum.Bit4)

c++操作为:& | ^ ~(用于和,或,xor,而不是位操作)。还有>>和<<,它们是位移位操作。

因此,要测试是否在标志中设置了位,你可以使用: 如果(flags & 8) //测试位4已设置