如何在C#中向用户请求输入

8

我正在从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#中要求用户输入内容?


什么是错误? - A3006
你必须先使用 Console.WriteLine(),然后再使用 Console.ReadLine() - Pikoh
Console.Write("Type any number:"); 或者 Console.WriteLine 然后你可以进行读取行操作。 - pinkfloydx33
5个回答

7
你应该更改这个:
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的符号),将会出现异常。要检查所输入的值是否正确:

(更好的选择):

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
}

一个重要的事情... 如果你不确定输入并想先检查它(这是个好主意),请尝试使用TryParse而不是Parse... - A3006
1
请注意,您现在可以内联声明变量:int.TryParse(Console.ReadLine(), out int x)。它将在 if 中可访问。 - Flater
@Flater,谢谢,已添加。 - Roman

1
Console.WriteLine("Type any number");
string input = Console.ReadLine();
int x;
if (int.TryParse(input, out x))
{
    //do your stuff here
}
else
{
    Console.WriteLine("You didn't enter number");
}

0
Console.WriteLine("Type any number: ");
string str = Console.ReadLine();
Type a = Type.Parse(str);

其中类型是您想将用户输入转换为的数据类型。我建议在求助论坛之前先阅读一些关于C#基础知识的书籍。


0
为了更加通用,我建议你创建一个额外的对象(因为在C#中你无法扩展静态对象),以实现你所指定的行为。
public static class ConsoleEx
{
    public static T ReadLine<T>(string message)
    {
        Console.WriteLine(message);
        string input = Console.ReadLine();
        return (T)Convert.ChangeType(input, typeof(T));
    }
}

当然,这段代码并不是没有错误的,因为它没有包含任何关于输出类型的约束条件,但仍然可以将其转换为某些类型而不会出现任何问题。

例如,使用此代码:

static void Main()
{
    int result = ConsoleEx.ReadLine<int>("Type any number: ");
    Console.WriteLine(result);
}

>>> Type any number: 
<<< 1337
>>> 1337 

在这里在线检查


-1

尝试一下

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接