在C#中使用enum作为整数常量

时间:2010-02-25 20:49:44

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

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

  

'InputManager.Add(ushort,Keys)'的最佳重载方法匹配有一些无效的参数
  参数'1':无法从'RegisteredInput'转换为'ushort'

如果我使用像manager.Add((ushort)RegisteredInput.Up, Keys.Q);这样的演员,它会起作用。但是因为演员必须是明确的,所以我想知道C#中是不是推荐的代码,就像在C ++中那样,并且有更好的方法(比如对每个值都使用const ushort,我有点不喜欢不太喜欢。

我到目前为止得到的最佳答案来自this thread,但听起来非常像黑客,我很担心。

谢谢!

3 个答案:

答案 0 :(得分:7)

使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) {...}    
}

答案 1 :(得分:7)

为什么不使用枚举来定义字典?有没有理由需要成为一个int?

public void add(RegisteredInput id, Keys key) {...}  

另外,一般来说,通常建议公开访问的成员(方法,类型等)应该是pascal cased(换句话说,Add而不是add)。

答案 2 :(得分:5)

对于Enums,我建议使用隐式强制转换:

public static class RegisteredInput {
    public const ushort Up = 0;
    public const ushort Down = 1;
    public const ushort Confirm = 2;
}
相关问题