c# flag comparison "only contain" a set

This question already has an answer here:

  • What does the [Flags] Enum Attribute mean in C#? 10 answers

  • First off, when defining a flags enum, each flag should represent a single bit in the enum:

    enum X { a = 1, b = 2, c = 4, d = 8 }
    

    This allows you to combine flags as well:

    CandD = 12, //has both c and d flags set.
    

    Or if you have a lot of them:

    enum X { 
      a = 1 << 0, 
      b = 1 << 1, 
      c = 1 << 2, 
      d = 1 << 3,
      ...
      CAndD = c | d
    }
    

    You can use a simple equality comparison to test if only certain flags are set.

    public bool ContainsOnly(X value, X flags) 
    {
         return value == flags;
    }
    
    public bool ContainsOnlyCandD(X value) 
    {
         return value == (X.c | X.d);
    }
    
    public bool ContainsBothCandDButCouldContainOtherStuffAsWell(X value) 
    {
         return (value & (X.c | X.d)) == (X.c | X.d);
    }
    

    Firstly, your flags should be created as such:

    [Flags]
    public enum StatusType
    {
        None = 0
        A = 1,
        B = 2,
        C = 4,
        D = 8,
        E = 16,
        F = 32,
        G = 64
    }
    

    You can then assign as such:

    var statusType = StatusType.A | StatusType.B;
    

    And test it as such:

    if (statusType.HasFlag(StatusType.A))
    {
        //A is defined
    }
    
    链接地址: http://www.djcxy.com/p/54448.html

    上一篇: 为什么枚举权限通常具有0,1,2,4的值?

    下一篇: c#标志比较“只包含”一组