c# - 我如何要求用户在 C# 中输入

标签 c# input console.readline

我正在从 Python 切换到 C#,但我在使用 ReadLine() 函数时遇到了问题。如果我想要求用户输入 Python,我是这样做的:

x = int(input("Type any number:  ")) 

在 C# 中,这变成了:

int x = Int32.Parse (Console.ReadLine()); 

但是如果我输入这个我会得到一个错误:

int x = Int32.Parse (Console.ReadLine("Type any number:  "));

如何要求用户在 C# 中键入内容?

最佳答案

你应该改变这个:

int x = Int32.Parse (Console.ReadLine("Type any number:  "));

为此:

Console.WriteLine("Type any number:  "); // or Console.Write("Type any number:  "); to enter number in the same line

int x = Int32.Parse(Console.ReadLine());

但是如果您输入一些字母(或另一个无法解析为 int 的符号),您将得到一个 Exception。检查输入的值是否正确:

(更好的选择):

Console.WriteLine("Type any number:  ");

int x;

if (int.TryParse(Console.ReadLine(), out x))
{
    //correct input
}
else
{
    //wrong input
}

C# 7 开始,您可以使用内联变量声明(out 变量):

Console.WriteLine("Type any number:  ");

if (int.TryParse(Console.ReadLine(), out var x)) // or out int x
{
    //correct input
}
else
{
    //wrong input
}

关于c# - 我如何要求用户在 C# 中输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42366766/

相关文章:

c# - 4.4 Bot Framework 中的 AzureBlobStorage 实现

c# - "The primary reference could not be resolved...."错误 - 我应该使用哪个包?

javascript - 正则表达式检测带括号的双引号 javascript 对象属性

java - 只会读取和写入一行

c# - 在 set 属性中使用 console.ReadLine()

c# - 以 .NET Standard 为目标并使用新的 csproj 格式的 VSIX flavor 项目

c++ - 读取字符并创建数组c++

一行中的C++可确定数组输入

c# - Console.ReadLine() 不在 C# 中保持控制台打开

c# - 学习 C#,编写了错误的程序,需要帮助了解为什么它不能按我想要的方式运行