Ric*_*cio 6 c# oop enums constants
我的问题很简单,但我找不到按照我希望的方式实现代码的方法.所以我开始想知道我想要实现的代码是不是很好.如果是,那么最好的方法是什么.
在这里:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
此代码将无法编译,会出现此类错误:
'InputManager.Add(ushort,Keys)'的最佳重载方法匹配有一些无效参数
参数'1':无法从'RegisteredInput'转换为'ushort'
如果我使用像manager.Add((ushort)RegisteredInput.Up, Keys.Q);它的演员会工作.但是因为演员必须是明确的,我想知道它是不是在C#中推荐的代码,就像它在C++中,如果有更好的方法(比如使用const ushort每个值,我有点不喜欢) .
到目前为止我得到的最佳答案来自这个帖子,但听起来很像黑客,我很担心.
谢谢!
使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) {...}
}
Run Code Online (Sandbox Code Playgroud)
为什么不使用枚举来定义字典?它有什么理由需要成为一个int吗?
public void add(RegisteredInput id, Keys key) {...}
Run Code Online (Sandbox Code Playgroud)
另外,一般来说,通常建议公开访问的成员(方法,类型等)应该是pascal cased(换句话说,Add而不是add).
对于Enums我需要隐式强制转换:
public static class RegisteredInput {
public const ushort Up = 0;
public const ushort Down = 1;
public const ushort Confirm = 2;
}
Run Code Online (Sandbox Code Playgroud)