Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

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);

运行示例 »


用户输入和数字

The 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: '输入字符串格式不正确。')。

您将在后面的章节中了解有关 异常 以及如何处理错误的更多信息。


C# 练习

通过练习测试自己

练习

填写缺失的部分以获取用户输入,并将其存储在变量 userName

Console.WriteLine("Enter username:");
 userName = Console.;
Console.WriteLine("Username is: " + userName);

开始练习


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.