C# 错误无法将类型“System.ConsoleKey”隐式转换为“char”

问题描述 投票:0回答:2

我编写的以下 C# 代码出现错误:

switch (Console.ReadKey(true).KeyChar)
{
    case ConsoleKey.DownArrow:
        Console.SetCursorPosition(x, y);
        break;
}

错误:

错误 1 无法将类型“System.ConsoleKey”隐式转换为“char”。存在显式转换(您是否缺少转换?)

怎么了?

c# .net compiler-errors console-application
2个回答
4
投票

您需要

Key
属性(返回
ConsoleKey
),而不是
KeyChar
(返回
char
)。

当有疑问时,如果编译器表明存在类型问题,您应该查看它期望什么以及实际得到什么 - 并找出其中哪些不是您所期望的。


2
投票

你需要

switch (Console.ReadKey(true).Key)
{
    case ConsoleKey.DownArrow:
        Console.SetCursorPosition(x,y);
        break;
}

相反。

常量

ConsoleKey.DownArrow
的类型为
ConsoleKey
,而
Console.ReadKey(true).KeyChar
的类型为
char
。由于
char
ConsoleKey
是不同的类型,因此此代码无法编译。相反,如果您使用 ReadKey 返回值的
Key
属性,您将得到一个
ConsoleKey
,它与 switch 语句中的 case 类型相同。

© www.soinside.com 2019 - 2024. All rights reserved.