在C#中使用enum作为整数常量
发布时间:2020-12-15 18:29:13 所属栏目:百科 来源:网络整理
导读:我的问题很简单,但我找不到按照我希望的方式实现代码的方法.所以我开始想知道我想要实现的代码是不是很好.如果是,那么最好的方法是什么. 在这里: class InputManager { SortedDictionaryushort,Keys inputList = new SortedDictionaryushort,Keys(); public
我的问题很简单,但我找不到按照我希望的方式实现代码的方法.所以我开始想知道我想要实现的代码是不是很好.如果是,那么最好的方法是什么.
在这里: 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(); } } 此代码将无法编译,会出现此类错误:
如果我使用像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) {...} } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |