I have this code:
if (PsionTeklogix.Keyboard.Keyboard.GetModifierKeyState(Key.Orange) == KeyState.Lock)
PsionTeklogix.Keyboard.Keyboard.InjectKeyboardCommand(Function.Orange, 0, 0);
if (PsionTeklogix.Keyboard.Keyboard.GetModifierKeyState(Key.Blue) == KeyState.Lock)
PsionTeklogix.Keyboard.Keyboard.InjectKeyboardCommand(Function.Blue, 0, 0);
if (PsionTeklogix.Keyboard.Keyboard.GetModifierKeyState(Key.Shift) == KeyState.Lock)
PsionTeklogix.Keyboard.Keyboard.InjectKeyboardCommand(Function.Shift, 0, 0);
if (PsionTeklogix.Keyboard.Keyboard.GetModifierKeyState(Key.Control) == KeyState.Lock)
PsionTeklogix.Keyboard.Keyboard.InjectKeyboardCommand(Function.Control, 0, 0);
...
and I want to refactor the code separating the key / function definition from the
actions. Key.xxx and Function.xxx aren’t from the same type.
eg: in Python, I could simply do something like:
keys = (
( Key.Orange, Function.Orange ),
( Key.Blue , Function.Blue ),
( Key.Shift , Function.Shift ),
...
)
psi_key = PsionTeklogix.Keyboard.Keyboard
for key, func in keys:
if psi_key.GetModifierKeyState(key) == KeyState.Lock):
psi_key.InjectKeyboardCommand(func, 0, 0)
What’s “the right way” to do in C#?
You can do something very similar:
You could even use LINQ if you wanted to:
Now using a
Dictionaryis somewhat odd here given that we’re not looking anything up. If you’re using .NET 4 you could use a list of tuples instead:and adjust the loop accordingly. You could use an anonymous type, too:
They’re all basically acting as ways of representing key/function pairs 🙂