在C#中使用enum作为整数常量

前端之家收集整理的这篇文章主要介绍了在C#中使用enum作为整数常量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的问题很简单,但我找不到按照我希望的方式实现代码方法.所以我开始想知道我想要实现的代码是不是很好.如果是,那么最好的方法是什么.

在这里:

  1. class InputManager
  2. {
  3. SortedDictionary<ushort,Keys> inputList = new SortedDictionary<ushort,Keys>();
  4.  
  5. public void Add(ushort id,Keys key) {...}
  6. public bool IsPressed(ushort id) {...}
  7. }
  8.  
  9. class Main
  10. {
  11. private enum RegisteredInput : ushort
  12. {
  13. Up,Down,Confirm
  14. }
  15.  
  16. public Main()
  17. {
  18. InputManager manager = new InputManager();
  19.  
  20. manager.Add(RegisteredInput.Up,Keys.Q);
  21. manager.Add(RegisteredInput.Down,Keys.A);
  22. manager.Add(RegisteredInput.Confirm,Keys.Enter);
  23. }
  24.  
  25. void update()
  26. {
  27. if(manager.IsPressed(RegisteredInput.Up)) action();
  28. }
  29. }

代码将无法编译,会出现此类错误

The best overloaded method match for ‘InputManager.Add(ushort,Keys)’ has some invalid arguments
Argument ‘1’: cannot convert from ‘RegisteredInput’ to ‘ushort’

@H_301_12@

如果我使用像manager.Add((ushort)RegisteredInput.Up,Keys.Q);它会工作.但是因为演员必须是明确的,我想知道它是不是在C#中推荐的代码,就像它在C中并且是否有更好的方法(比如对每个值使用const ushort,我有点不喜欢)许多).

到目前为止我得到的最佳答案是this thread,但听起来很像黑客,我很担心.

谢谢!

解决方法

使InputManager成为通用类型. IE:
  1. class InputManager<T>
  2. {
  3. SortedDictionary<T,Keys> inputList = new SortedDictionary<T,Keys>();
  4.  
  5. public void add(T id,Keys key) {...}
  6. public bool isPressed(T id) {...}
  7. }

猜你在找的C#相关文章