Using enum as integer constant in C#
My questio开发者_运维问答n is pretty simple, but I didn't find a way to implement my code the way I want it to be. So I started wondering if the code I want to implement is not good. And if it is, what's the best way to do it.
Here it goes:
class InputManager
{
SortedDictionary<ushort,Keys> inputList = new SortedDictionary<ushort,Keys>();
public void Add(ushort id, Keys key) {...}
public bool IsPressed(ushort id) {...}
}
class Main
{
private enum RegisteredInput : ushort
{
Up,
Down,
Confirm
}
public Main()
{
InputManager manager = new InputManager();
manager.Add(RegisteredInput.Up, Keys.Q);
manager.Add(RegisteredInput.Down, Keys.A);
manager.Add(RegisteredInput.Confirm, Keys.Enter);
}
void update()
{
if(manager.IsPressed(RegisteredInput.Up)) action();
}
}
This code won't compile, giving errors of this kind:
The best overloaded method match for 'InputManager.Add(ushort, Keys)' has some invalid arguments
Argument '1': cannot convert from 'RegisteredInput' to 'ushort'
If I use a cast like in manager.Add((ushort)RegisteredInput.Up, Keys.Q);
it will work. But because the cast must be explicit, I was wondering if it is not recomended code in C# like it is in C++ and if there is a better way of doing it (like using const ushort
for every value, which I kinda don't like much).
The best answer I got so far was from this thread, but it sounds so much like a hack, I got worried.
Thanks!
Make InputManager a generic type. IE:
class InputManager<T>
{
SortedDictionary<T,Keys> inputList = new SortedDictionary<T,Keys>();
public void add(T id, Keys key) {...}
public bool isPressed(T id) {...}
}
Why not just define the dictionary using your enumeration? Is there a reason it needs to be an int?
public void add(RegisteredInput id, Keys key) {...}
Also, as an aside, it's generally recommended that publicly-acessible members (methods, types, etc.) should be pascal cased (in other words, Add
instead of add
).
The implicit cast is necessary for Enums I recommend this:
public static class RegisteredInput {
public const ushort Up = 0;
public const ushort Down = 1;
public const ushort Confirm = 2;
}
精彩评论