为什么不能将 Console.ReadKey() 放在显示到控制台的文本前面,或者将 Console.ReadKey() 分配给变量?

Why can't you put Console.ReadKey() in front of the text displayed to the console, or assign Console.ReadKey() to a variable?

using System;

class MainClass {
  public static void Main (string[] args) {
    Console.WriteLine("Press any key to continue...");
    Console.WriteLine(" key pressed", Console.ReadKey());
  }
}

此代码有效并且没有错误但是

using System;

class MainClass {
  public static void Main (string[] args) {
    Console.WriteLine("Press any key to continue...");
    Console.WriteLine(Console.ReadKey(), " key pressed");
  }
}

这不起作用,我得到一个错误

Error CS1502: the best overload method match for 'System.Console.WriteLine(string, object)' has some invalid arguments

Error CS1503: Argument '#1' cannot convert 'System.ConsoleKeyInfo' expression to type 'string'

我是 C# 的新手,所以我不太了解这种语言(以前只用过 Python),但在 Python 中,我会把这段代码写成

keyPressed = input("Type a key(s) ")
print(keyPressed, "is the key(s) you pressed")

我也不能只将 ReadKey() 分配给变量

var keyPressed = Console.ReadKey();
Console.WriteLine("the key you pressed was {0}", keyPressed);

对于上面的代码块,我想将用户按下的任何键存储在变量 keyPressed 中,但它不起作用。

我的问题是为什么你不能把 Console.ReadKey() 放在我想在控制台上显示的文本前面,或者将 Console.ReadKey() 分配给一个变量,你怎么会有任何键用户按下分配给变量?

可以,但需要这样使用

Console.Write("Type a key: ");
var k = Console.ReadKey();
Console.WriteLine();
Console.WriteLine($"You have pressed {k.KeyChar}");

您正在使用方法 Console.WriteLine(),其中 很多重载,例如 :

  • Console.WriteLine(String)
  • Console.WriteLine(Int64)
  • Console.WriteLine(String, Object)

等等等等。但是没有过载:

  • Console.WriteLine(Object, String)

而后者是您在执行 Console.WriteLine(Console.ReadKey(), " key pressed");

时尝试使用的那个

你的Console.ReadKey()return一个ConsoleKeyInfo一个String 派生自 String 或您可以在重载中找到的任何其他对象。因此,由于它不存在,因此无法正常工作,您会收到您提到的错误。

通常您可以使用自动完成功能找出方法的重载或查看文档,这主要是查找和理解事物的最佳方式。

希望对您有所帮助。