在 C# 中使用 enum 作为整型常量
我的问题很简单,但我没有找到一种方法来按照我想要的方式实现我的代码。所以我开始怀疑我想要实现的代码是否不好。如果是的话,最好的方法是什么?
事情是这样的:
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();
}
}
这段代码将无法编译,并给出此类错误:
“InputManager.Add(ushort, Keys)”的最佳重载方法匹配有一些无效参数
参数“1”:无法从“RegisteredInput”转换为“ushort”
如果我使用类似于 manager.Add((ushort)RegisteredInput.Up, Keys.Q);
中的强制转换,它将起作用。但因为强制转换必须是显式的,所以我想知道 C# 中是否不推荐像 C++ 中那样的代码,以及是否有更好的方法(例如对每个值使用 const ushort ),我不太喜欢)。
到目前为止,我得到的最佳答案来自 此线程,但这听起来很像黑客,我很担心。
谢谢!
My question is pretty simple, but I didn't find a way to implement my code the way I want it to be. So I started wondering if the code I want to implement is not good. And if it is, what's the best way to do it.
Here it goes:
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();
}
}
This code won't compile, giving errors of this kind:
The best overloaded method match for 'InputManager.Add(ushort, Keys)' has some invalid arguments
Argument '1': cannot convert from 'RegisteredInput' to 'ushort'
If I use a cast like in manager.Add((ushort)RegisteredInput.Up, Keys.Q);
it will work. But because the cast must be explicit, I was wondering if it is not recomended code in C# like it is in C++ and if there is a better way of doing it (like using const ushort
for every value, which I kinda don't like much).
The best answer I got so far was from this thread, but it sounds so much like a hack, I got worried.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使 InputManager 成为泛型类型。 IE:
Make InputManager a generic type. IE:
为什么不直接使用枚举来定义字典呢?有理由需要它是 int 吗?
另外,顺便说一句,通常建议可公开访问的成员(方法、类型等)应采用 pascal 大小写(换句话说,
Add
而不是add
) 。Why not just define the dictionary using your enumeration? Is there a reason it needs to be an int?
Also, as an aside, it's generally recommended that publicly-acessible members (methods, types, etc.) should be pascal cased (in other words,
Add
instead ofadd
).隐式转换对于枚举是必要的,我建议这样做:
The implicit cast is necessary for Enums I recommend this: