为什么 Convert.ToInt32( Console.Read() ) 返回 53 而不是 5?

-1 c#

这个程序:

static void Main(string[] args)
{
    int x;
    Console.Write("Enter number:");
    x = Convert.ToInt32(Console.Read());
    Console.WriteLine($"Output: {x}");
}
Run Code Online (Sandbox Code Playgroud)

控制台文本:

Enter number: 5
Output: 53

Press any key to continue...
Run Code Online (Sandbox Code Playgroud)

截屏:

在此处输入图片说明

输入数字 5 但输出不是 5

Dai*_*Dai 5

  • Console.Read()单个字符读作 a char,而不是将整行读作 a string
  • char 值实际上是整数本身,对于大多数操作,C#/.NET 不会将其作为文本处理,这可能会让初学者望而却步。
  • '5'(as a char)的整数值在 ASCII 和 Unicode 中是 53
  • Convert.ToInt32(Char)对待char为整数(所以值'5'53其一个),并转换Int32值,而不是解析字符为十进制数。
    • 我强烈建议避免Convert上课。.NET Framework 中有更好的替代方案(例如Int32.TryParse)。

要解决此问题,请使用Console.ReadLine()andInt32.TryParse代替,Convert.ToInt32以便您可以优雅地处理无效输入。

while( true )
{
    Console.Write( "Enter number: " );
    String input = Console.ReadLine();
    if( Int32.TryParse( input, out Int32 value ) ) // ideally use the overload with NumberStyles.Any and CultureInfo.CurrentCulture to be explicit.
    {
        Console.WriteLine( $"Output: {value}" );
    }
    else
    {
        Console.WriteLine( "Please enter a valid number." ); 
    }
}
Run Code Online (Sandbox Code Playgroud)