我知道用于使用Convert.To
方法读取输入,但除此之外是否有任何方法可以阅读。
int k = Convert.ToInt16(Console.ReadLine());
答案 0 :(得分:5)
从控制台应用程序读取输入的最简单方法是Console.ReadLine
。有可能的替代方案,但它们更复杂,适用于特殊情况:请参阅Console.Read或Console.ReadKey。
重要的是转换为整数不能使用Convert.ToInt32
或Int32.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
的原因在于您可以检查是否可以转换为整数。相反,其他方法会引发一个异常,您应该处理代码流的复杂化。
答案 1 :(得分: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();
}
}
答案 2 :(得分: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();
答案 3 :(得分:1)
以下是您可以遵循的替代方案method:
int k;
if (int.TryParse(Console.ReadLine(), out k))
{
//Do your stuff here
}
else
{
Console.WriteLine("Invalid input");
}
答案 4 :(得分:1)
有三种类型的整数:
1。)Short Integer:16位数(-32768到32767)。在c#中,您可以将一个短整数变量声明为short
或Int16
。
2。)"Normal" Integer:32位数字(-2147483648到2147483647)。使用关键字int
或Int32
声明一个整数。
3。)Long Integer:64位数字(-9223372036854775808至9223372036854775807)。使用long
或Int64
声明一个长整数。
区别在于您可以使用的数字范围。
您可以使用Convert.To
,Parse
或TryParse
转换它们。