我的问题很简单,但我没有找到一种方法来按照我想要的方式实现我的代码。于是我开始怀疑是不是我要实现的代码不好。如果是,最好的方法是什么。
这里是:
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
Argument '1': cannot convert from 'RegisteredInput' to 'ushort'
如果我在 manager.Add((ushort)RegisteredInput.Up, Keys.Q);
中使用强制转换,它将起作用。但是因为转换必须是显式的,我想知道它是否不像在 C++ 中那样在 C# 中被推荐使用,是否有更好的方法(比如对每个值使用 const ushort
,我有点不太喜欢)。
到目前为止,我得到的最佳答案来自 this thread ,但这听起来很像黑客攻击,我很担心。
谢谢!
最佳答案
使 InputManager 成为通用类型。即:
class InputManager<T>
{
SortedDictionary<T,Keys> inputList = new SortedDictionary<T,Keys>();
public void add(T id, Keys key) {...}
public bool isPressed(T id) {...}
}
关于c# - 在 C# 中使用枚举作为整型常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2337515/