键(枚举)到字符串

Mel*_*sus 4 c# enums key

如何将Key(KeyEventArgs中的Key)转换为字符串.

例如,如果用户输入" - ":

e.Key.ToString() = "Subtract"
new KeyConverter().ConvertToString(e.Key) = "Subtract"
Run Code Online (Sandbox Code Playgroud)

我想要的是得到" - "的结果,而不是"Substract"......

Ry-*_*Ry- 7

使用Dictionary<TKey, TValue>:

类级别:

private readonly Dictionary<string, string> operations = new Dictionary<string, string>;

public ClassName() {
    // put in constructor...
    operations.Add("Subtract", "-");
    // etc.
}
Run Code Online (Sandbox Code Playgroud)

在您的方法中,只需使用operations[e.Key.ToString()].

编辑:实际上,为了更高效率:

private readonly Dictionary<System.Windows.Input.Key, char> operations = new Dictionary<System.Windows.Input.Key, char>;

public ClassName() {
    // put in constructor...
    operations.Add(System.Windows.Input.Key.Subtract, '-');
    // etc.
}
Run Code Online (Sandbox Code Playgroud)

在您的方法中,只需使用operations[e.Key].