我正在从 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/