c# - 在 C# 中使用枚举作为整型常量

标签 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();
    }
}

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

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/

相关文章:

时间:2019-03-17 标签:c#XMLSerializer返回null

php - OOP - session 和 PHP

perl - 在 Perl 中,如何将函数作为另一个函数的参数传递?

c# - UInt32 的底层枚举类型导致编译器错误

java - play framework - 在路由中绑定(bind)枚举

c# - 如何防止多张图片相互重叠

c# - 从枚举集合中删除foreach循环项

c# - RDLC 多列排序 : Sorts Numbers as Strings Issue

java - 如何影响一个类的所有对象? ( java )

groovy - 在 Groovy 脚本中导入内部枚举