给定以下标志,
[Flags]
public enum Operations
{
add = 1,
subtract = 2,
multiply = 4,
divide = 8,
eval = 16,
}
如何实现 IF 条件来执行每个操作?在我的尝试中,第一个条件适用于添加、评估, 哪个是对的。然而第一个条件也适用于减法、求值,这是不正确的。
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;
}
我看不出问题是什么。
改变你的内在&
to |
:
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))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)