-2
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");
  }
}

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

错误 CS1502:“System.Console.WriteLine(string, object)”的最佳重载方法匹配有一些无效参数

错误 CS1503:参数“#1”无法将“System.ConsoleKeyInfo”表达式转换为“字符串”类型

我是 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()给一个变量,你如何将用户按下的任何键分配给一个变量?

4

2 回答 2

1

你可以,但你需要以这种方式使用它

Console.Write("Type a key: ");
var k = Console.ReadKey();
Console.WriteLine();
Console.WriteLine($"You have pressed {k.KeyChar}");
于 2020-01-18T19:38:24.210 回答
1

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

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

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

  • Console.WriteLine(Object, String)

后者是你在做的时候试图使用的那个Console.WriteLine(Console.ReadKey(), " key pressed");

Console.ReadKey()返回的不是a ,它不是从重载中可以找到的任何其他对象或任何其他对象派生的。因此,由于它不存在,因此它无法工作,并且您会收到您提到的错误。ConsoleKeyInfo StringString

通常您可以使用自动补全来找出方法的重载或查看文档,这通常是查找和理解事物的最佳方式。

希望这可以帮助。

于 2020-01-18T19:49:15.127 回答