-3

我知道通过使用Convert.To方法读取输入,但是除此之外还有什么方法可以读取。

int k = Convert.ToInt16(Console.ReadLine()); 
4

5 回答 5

5

从控制台应用程序读取输入的最简单方法是Console.ReadLine. 有可能的替代方案,但它们更复杂并保留用于特殊情况:请参阅Console.ReadConsole.ReadKey

然而,重要的是转换为不应使用Convert.ToInt32orInt32.Parse而是使用的整数Int32.TryParse

int k = 0;
string input = Console.ReadLine();
if(Int32.TryParse(input, out k))
    Console.WriteLine("You have typed a valid integer: " + k);
else
    Console.WriteLine("This: " + input + " is not a valid integer");

使用的原因Int32.TryParse在于您可以检查是否可以转换为整数。相反,其他方法会引发异常,您应该处理使代码流复杂化的异常。

于 2016-01-22T09:03:10.280 回答
3

您可以为 Console 创建自己的实现并在任何您想要的地方使用它:

public static class MyConsole
{
    public static int ReadInt()
    {
        int k = 0;
        string val = Console.ReadLine();
        if (Int32.TryParse(val, out k))
            Console.WriteLine("You have typed a valid integer: " + k);
        else
            Console.WriteLine("This: " + val + " is not a valid integer");
        return k;
    }

    public static double ReadDouble()
    {
        double k = 0;
        string val = Console.ReadLine();
        if (Double.TryParse(val, out k))
            Console.WriteLine("You have typed a valid double: " + k);
        else
            Console.WriteLine("This: " + val + " is not a valid double");
        return k;
    }
    public static bool ReadBool()
    {
        bool k = false;
        string val = Console.ReadLine();
        if (Boolean.TryParse(val, out k))
            Console.WriteLine("You have typed a valid bool: " + k);
        else
            Console.WriteLine("This: " + val + " is not a valid bool");
        return k;
    }
}

class Program
{
    static void Main(string[] args)
    {
        int s = MyConsole.ReadInt();
    }

}
于 2016-01-22T09:15:21.550 回答
1

整数有 3 种类型:

1.)短整数:16 位数字(-32768 到 32767)。在 c# 中,您可以将短整型变量声明为shortInt16

2.) “普通”整数:32 位数字(-2147483648 到 2147483647)。int用关键字or声明一个整数Int32

3.)长整数:64 位数字(-9223372036854775808 到 9223372036854775807)。long用or声明一个长整数Int64

不同之处在于您可以使用的数字范围。您可以使用 或 转换Convert.To它们。ParseTryParse

于 2016-01-22T09:31:03.377 回答
1

您可以使用int.TryParse

看例子

var item = Console.ReadLine();
int input;
if (int.TryParse(item, out input))
{
    // here you got item as int in input variable.
    // do your stuff.
    Console.WriteLine("OK");
}
else
    Console.WriteLine("Entered value is invalid");

Console.ReadKey();
于 2016-01-22T09:04:56.837 回答
1

这是您可以遵循的另一种最佳方法

int k;
if (int.TryParse(Console.ReadLine(), out k))
   {
      //Do your stuff here
   }
else 
   {
      Console.WriteLine("Invalid input");
   }
于 2016-01-22T09:05:10.473 回答