如何实现从整数获取ConsoleKey枚举值的函数?
解决通过整数CODE获取对应ConsoleKey的问题
核心思路
ConsoleKey是枚举类型,底层存储的是整数值,所以可以通过枚举转换将整数CODE转为对应的ConsoleKey枚举值,而非像数组那样用索引访问。
修正后的函数实现
方案1:直接强制转换(适用于确定CODE是有效ConsoleKey值的场景)
若能保证传入的key参数是合法的ConsoleKey数值,直接强制转换即可:
public bool GetKey(ConsoleKeyInfo cki, int key) { // 将整数CODE转为ConsoleKey枚举 ConsoleKey targetKey = (ConsoleKey)key; // 用传入的cki判断,无需重复读取按键 return cki.Key == targetKey; }
方案2:安全转换(避免无效CODE导致异常)
若不确定CODE是否合法,用Enum.TryParse做安全转换,防止抛出异常:
public bool GetKey(ConsoleKeyInfo cki, int key) { if (Enum.TryParse(key.ToString(), out ConsoleKey targetKey)) { return cki.Key == targetKey; } // 转换失败时返回false return false; }
方案3:函数内部读取按键(无需传入ConsoleKeyInfo)
如果函数需要自行读取按键,可去掉多余参数:
public bool GetKey(int key) { if (Enum.TryParse(key.ToString(), out ConsoleKey targetKey)) { return Console.ReadKey(true).Key == targetKey; } return false; }
为什么不能用ConsoleKey[key]?
ConsoleKey是枚举类型,不是数组或带有索引器的类,因此无法通过[key]的方式访问。必须通过枚举转换,将整数映射为对应的枚举成员。
内容的提问来源于stack exchange,提问作者Inferno
相关产品推荐
相关产品推荐

