【发布时间】:2015-08-05 11:02:19
【问题描述】:
1)
class Program
{
static void Main(string[] args)
{
int a;
a = Convert.ToInt32( "a" );
Console.Write(a);
}
}
我收到FormatException 的消息:Input string was not in a correct format。这个就很好理解了。
2)
class Program
{
static void Main(string[] args)
{
int a;
a = Convert.ToInt32( Console.Read() );
Console.Write(a);
}
}
在第二种情况下,我可以输入任何字符,例如abc,它会显示在控制台中。
问题:为什么在第二种情况下不抛出 FormatException 以及为什么它与非 int 字符一起成功?
更新
使用Console.ReadLine() 方法,返回string 类型,也不会删除FormatException 并成功打印控制台中的任何字符。
class Program
{
static void Main(string[] args)
{
int a;
a = Convert.ToInt32(Console.ReadLine());
Console.Write(a);
}
}
【问题讨论】:
-
简单的答案,只需在 Visual Studio 中将鼠标悬停在 .Read() 上查看文档或事件的第一行
-
是的,
Console.Read()返回int类型,但是如果使用返回console.ReadLine()类型的console.ReadLine()方法,此代码也不会抛出异常并且有效 -
"如果使用返回字符串类型的 console.ReadLine() 方法,此代码也不会抛出异常并且可以工作" - 不,那不是真的。显示后一个声明的代码和您的输入。
-
@CodeCaster - 请查看有问题的更新
-
是的,“输入”是指您输入的内容。
Console.ReadLine()等待 Enter 键...它打印您键入的字符,但仅在您按 Enter 后返回输入。然后你会得到你的例外。