C# 用户输入
获取用户输入
您已经学过 Console.WriteLine()
用于输出(打印)值。现在我们将使用 Console.ReadLine()
来获取用户输入。
在下面的示例中,用户可以输入他们的用户名,该用户名存储在变量 userName
中。然后我们打印 userName
的值。
示例
// Type your username and press enter
Console.WriteLine("Enter username:");
// Create a string variable and get user input from the keyboard and store it in the variable
string userName = Console.ReadLine();
// Print the value of the variable (userName), which will display the input value
Console.WriteLine("Username is: " + userName);
用户输入和数字
Console.ReadLine()
方法返回一个 string
。因此,您无法从其他数据类型(如 int
)获取信息。以下程序将导致错误。
示例
Console.WriteLine("Enter your age:");
int age = Console.ReadLine();
Console.WriteLine("Your age is: " + age);
错误消息将类似如下内容
无法隐式将类型“string”转换为“int”
正如错误消息所示,您不能隐式地将类型“string”转换为“int”。
幸运的是,您在 上一章(类型转换) 中已经学过,您可以使用 Convert.To
方法之一显式地转换任何类型。
示例
Console.WriteLine("Enter your age:");
int age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your age is: " + age);
注意:如果您输入了错误的信息(例如,在数字输入中输入文本),您将收到一个异常/错误消息(例如 System.FormatException: “输入字符串的格式不正确。”)。
您将在后面的章节中了解更多关于 异常 以及如何处理错误的信息。