C# 枚举标志比较

标签 c# enums

给定以下标志,

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

如何实现 IF 条件来执行每个操作?在我的尝试中,第一个条件对于 add, eval 为真,这是正确的。然而,第一个条件对于 subtract, eval 也是正确的,这是不正确的。

        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;
    }

我看不出问题是什么。

最佳答案

将你的内部 & 更改为 |:

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

这相当于:

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

这可能更具可读性。您可能还想考虑这样的扩展:

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

然后你可以这样做:

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

这可能更具可读性。最后,您可以创建此扩展以获得更多乐趣:

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

那么你的表情可能会变成:

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

关于C# 枚举标志比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2567307/

相关文章:

c# - 取回匿名类型

c# - 线程锁内的多线程

java - 在 Java 中实现通用接口(interface)的枚举常量

c# - Console.WriteLine(Enum.Value) 在 C# 和 VB.Net 中给出不同的输出

c# - 在内存中创建 FileStream 而不是在磁盘上保存一个物理文件

c# - 嵌套母版页和 .FindControl

java - 在 EnumSet 和 boolean 值数组之间转换

c# - 单独的枚举类?

java - 枚举多模式

c# - 在 Unity 中将通用存储库与 TEntity 结合使用