简体   繁体   English

我如何要求用户输入C#

[英]How do I ask the user for input in C#

I am switching from Python to C# and I am having trouble with the ReadLine() function. 我正在从Python切换到C#,我遇到了ReadLine()函数的问题。 If I want to ask a user for input Python I did it like this: 如果我想要求用户输入Python,我就是这样做的:

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

In C# this becomes: 在C#中,这变为:

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

But if I type this I get an error: 但是如果我输入这个,我会收到一个错误:

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

How do I ask the user to type something in C#? 如何让用户在C#中输入内容?

You should change this: 你应该改变这个:

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

to this: 对此:

Console.WriteLine("Type any number:  "); // or Console.Write("Type any number:  "); to enter number in the same line
int x = Int32.Parse(Console.ReadLine());

But if you enter some letter(or another symbol that cannot be parsed to int ) you will get an Exception . 但是如果你输入一些字母(或另一个无法解析为int符号),你将得到一个Exception To check if entered value is correct: 要检查输入的值是否正确:

(Better option): (更好的选择):

Console.WriteLine("Type any number:  ");
int x;
if (int.TryParse(Console.ReadLine(), out x))
{
    //correct input
}
else
{
    //wrong input
}
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");
}
Console.WriteLine("Type any number: ");
string str = Console.ReadLine();
Type a = Type.Parse(str);

where Type is Data Type you want to cast user input to. 其中Type是您要将用户输入转换为的数据类型。 I suggest reading few books on C# fundaments before turning to forums. 我建议在转向论坛之前阅读几本关于C#基础知识的书籍。

To be more generic I would suggest you to make an additional object ( because you cannot extend static objects in C# ) to behave like you've specified. 为了更通用,我建议你创建一个额外的对象(因为你不能在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));
    }
}

Of course you this code is not error free because it does not contains any constraints about the output type but still It will cast into some types without any problems. 当然你这个代码不是没有错误的,因为它不包含任何关于输出类型的约束但是它仍会被转换成某些类型而没有任何问题。

For example. 例如。 Using this code : 使用此代码:

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

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

Check this online 在线查看

try this 试试这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM