C# Enum Flags Comparison

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

Given the following flags,

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


        
5条回答
  •  旧时难觅i
    2021-02-09 10:55

    The reason your operation is failing is because you have the wrong expression. (Operations.add & Operations.eval) is always zero. Left and right side of your first comparison are both always zero. Try this instead - I suspect it's what you were after:

    public double Evaluate(double input)
    {
        if ((operation & (Operations.add | Operations.eval)) == (Operations.add | Operations.eval))
            currentResult += input;
        else if ((operation & (Operations.subtract | Operations.eval)) == (Operations.subtract | Operations.eval))
            currentResult -= input;
        else
            currentResult = input;
    
        operation = null;
    
        return currentResult;
    }
    

提交回复
热议问题