C# Enum Flags Comparison

前端 未结 5 898
心在旅途
心在旅途 2021-02-09 10:03

Given the following flags,

  [Flags]
    public enum Operations
    {
        add = 1,
        subtract = 2,
        multiply = 4,
        divide = 8,
        ev         


        
5条回答
  •  [愿得一人]
    2021-02-09 10:48

    Change your inner & to |:

    if ((operation & (Operations.add | Operations.eval)) == (Operations.add | Operations.eval))
    

    This is equivalent to:

    if( ((operation & Operations.add)==Operations.add) &&
        ((operation & Operations.eval)==Operations.eval))
    

    which might be more readable. You might also want to consider an Extension like this:

    public static bool HasFlag(this Operations op, Operations checkflag)
    {
        return (op & checkflag)==checkflag;
    }
    

    then you can do this:

    if(operation.HasFlag(Operations.add) && Operations.HasFlag(Operations.eval))
    

    which might be even more readable. Finally you could create this extension for even more fun:

    public static bool HasAllFlags(this Operations op, params Operations[] checkflags)
    {
        foreach(Operations checkflag in checkflags)
        {
            if((op & checkflag)!=checkflag)
                return false;
        }
        return true;
    }
    

    Then your expression could turn into:

    if(operation.HasAllFlags(Operations.add, Operations.eval))
    

提交回复
热议问题