给定以下标志,
[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/