6

我正在从 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# 中键入内容?

4

5 回答 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),您将得到一个Exception. 要检查输入的值是否正确:

(更好的选择):

Console.WriteLine("Type any number:  ");
int x;
if (int.TryParse(Console.ReadLine(), out x))
{
    //correct input
}
else
{
    //wrong input
}
于 2017-02-21T12:02:28.470 回答
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");
}
于 2017-02-21T12:05:00.827 回答
0
Console.WriteLine("Type any number: ");
string str = Console.ReadLine();
Type a = Type.Parse(str);

其中 Type 是您要将用户输入转换为的数据类型。我建议在转向论坛之前阅读几本关于 C# 基础的书籍。

于 2017-02-21T12:06:34.347 回答
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 

上网查这个

于 2017-02-21T12:17:03.173 回答
-1

尝试这个

Console.WriteLine("Type any number:  ");
int x = Int32.Parse (Console.ReadLine());
于 2017-02-21T12:02:54.113 回答