bitwise join two if's into one
I have this,
public enum Condition : uint // bitwise
{
None = 0,
NewLine = 1,
Space = 2
}
Rule.Condition someCondition = Rule.Condition.Space | Rule.Condition.NewLine;
I'd like to convert this,
if ((Rule.Condition.Space & condition) == Rule.Condition.Space) return true;
if ((Rule.Condition.NewLine & condition) == Rule.Condition.NewLine) return true;
Into something like,
if((someCondition & condition) =开发者_如何学C= someCondition) return true;
But it isn't working. What am I forgetting?
Well, if you're just wanting to test for none, then check for > 0
. But, if you're looking for a less specific solution, something like this would combine the two and remove the if
altogether:
return (int)(someCondition & (Condition.Space | Condition.NewLine)) > 0
There is a special convenience method HasFlag
in .NET4 expressly for this purpose:
if (condition.HasFlag(someCondition)) return true;
Here's the docs:
- Enum.HasFlag Method
someCondition
has two bits set, one for Rule.Condition.Space
and one for Rule.Condition.NewLine
. someCondition & condition
will have one bit set if condition
is Space or NewLine, and be 0
otherwise.
You should test if the bitwise operation returns 0
instead of checking for equality with someCondition
if ((someCondition & condition) != 0) return true
精彩评论