Reputation: 3429
Im working on some input handling and i wanted to implement a shorthand for this
if (KeyboardEvents.Down.Contains(Keys.LeftShift) || KeyboardEvents.Down.Contains(Keys.RightShift))
into this
if (KeyboardEvents.Down.Contains(Keys.LeftShift | Keys.RightShift))
I have seen this kind of syntax a few times used within attributes like this.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
I'm not sure if its at all possible to do the way I want to, but it would be a fancy shorthand simplifying several if's.
Yes the shorthand compiles, so obviously it does something, but not what I thought it would (so another question to the problem is, what does it actually do?).
here is the structure behind the keyboard input handling.
public static class KeyboardEvents
{
public static KeyboardState State { get { return Keyboard.GetState(); } }
public static Keys[] Down = new Keys[0];
public static IEnumerable<Keys> WasDown = new Keys[0];
public static void Update(GameTime gameTime)
{
Keys[] NewDown = State.GetPressedKeys();
WasDown = Down.Except(NewDown);
Down = NewDown;
}
}
Upvotes: 2
Views: 64
Reputation: 129
You can turn it around and say
if({Keys.LeftShift, Keys.RightShift}.contains(KeyboardEvents.Down)).
Upvotes: 2
Reputation: 149548
The bitwise OR and logical OR have different meanings. The former will do a bitwise or between two flags, meaning:
Class = 0x0004,
Struct = 0x0008,
Will make the enum value of AttributeTarget
equal to 0x0012
which is bitwise OR between the two values.
You can see this yourself with a simple example:
var targetAttributes = AttributeTargets.Class | AttributeTargets.Struct;
Console.WriteLine((int)targetAttributes);
The logical OR means "Evaluate the left hand expression, if it evaluates to true, follow through the branch. Otherwise, evaluate the right hand expression, if it evaluates to true, follow the branch".
If KeyboardEvents
is an enum
, you can use Enum.HasFlag
to see if any of the flags are set:
if (KeyboardEvents.HasFlag(Keys.LeftShift | Keys.RightShift))
{
// Do stuff.
}
Upvotes: 4