我的问题很简单,但我找不到按照我希望的方式实现代码的方法.所以我开始想知道我想要实现的代码是不是很好.如果是,那么最好的方法是什么.
在这里:
- 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();
- }
- }
The best overloaded method match for ‘InputManager.Add(ushort,Keys)’ has some invalid arguments
@H_301_12@
Argument ‘1’: cannot convert from ‘RegisteredInput’ to ‘ushort’如果我使用像manager.Add((ushort)RegisteredInput.Up,Keys.Q);它会工作.但是因为演员必须是明确的,我想知道它是不是在C#中推荐的代码,就像它在C中并且是否有更好的方法(比如对每个值使用const ushort,我有点不喜欢)许多).
到目前为止我得到的最佳答案是this thread,但听起来很像黑客,我很担心.
谢谢!
解决方法
使InputManager成为通用类型. IE:
- class InputManager<T>
- {
- SortedDictionary<T,Keys> inputList = new SortedDictionary<T,Keys>();
- public void add(T id,Keys key) {...}
- public bool isPressed(T id) {...}
- }