C#枚举标志比较 [英] C# Enum Flags Comparison
问题描述
鉴于以下标志,
[Flags]
public枚举操作
{
add = 1,
subtract = 2,
multiply = 4,
divide = 8,
eval = 16,
}
如何实现一个IF条件来执行每个操作?在我的尝试中,第一个条件是对于 add,eval 是正确的。然而,第一个条件也适用于减法,eval ,这是不正确的。
public double Evaluate(double input)
{
if((operation&(Operations.add & Operations.eval))==(Operations.add& Oper.eval))
currentResult + = input;
else if((operation&(Operations.subtract& Oper.eval))==(Operations.subtract& Operations.eval))
currentResult - = input;
else
currentResult = input;
operation = null;
return currentResult;
}
我看不到有什么问题。
将内部&
更改为 |
:
if((operation&(Operations.add | Operations.eval))==(Operations.add | eval))
这相当于:
< $($)$($)$($)$($)$($)$($) ))
这可能更可读。您可能还想考虑一下这样的扩展:
public static bool HasFlag(this Operations op,Operations checkflag)
{
return(op& checkflag)== checkflag;
}
那么你可以这样做:
if(operation.HasFlag(Operations.add)&& Operations.HasFlag(Operations.eval))
pre>
这可能更加可读。最后,您可以创建这个扩展更加有趣:
public static bool HasAllFlags(this Operations op,params Operations [] checkflags)
{
foreach(checkflags中的操作checkflag)
{
if((op& checkflag)!= checkflag)
return false;
}
返回true;
}
然后,您的表达式可能会变成:
if(operation.HasAllFlags(Operations.add,Operations.eval))
Given the following flags,
[Flags] public enum Operations { add = 1, subtract = 2, multiply = 4, divide = 8, eval = 16, }
How could I implement an IF condition to perform each operation? In my attempt, the first condition is true for add, eval, which is correct. However the first condition is also true for subtract, eval, which is incorrect.
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; }
I cannot see what the problem is.
解决方案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))
这篇关于C#枚举标志比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!