【问题标题】:How to fix the best overloaded method match has some invalid arguments?如何修复最佳重载方法匹配有一些无效参数?
【发布时间】:2019-07-30 01:45:31
【问题描述】:

我收到标题中的错误,代码有什么问题?我认为这是一个语法错误,但我不确定,因为我没有太多关于错误实际含义的信息。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{

class Program
{

    static void Main(string[] args)
    {

        Console.WriteLine("Please Input Number of Rows you want to make in your pyrimid: ");

        int num = int.Parse(Console.Read()); // error here

        Console.WriteLine(num);// Just to check if it is getting the right number
        Console.Read();//This is Here just so the console window doesn't close when the program runs

    }
}
}

编辑:

为了澄清,我希望代码只是从用户那里获取一个数字,然后打印用户输入的数字。

【问题讨论】:

    标签: c#


    【解决方案1】:

    int.Parse 接受字符串作为参数。使用Console.ReadLine()从用户那里获取一个字符串,然后将其传递给int.Parse

    int num = int.Parse(Console.ReadLine());
    

    请注意,如果用户输入无法识别为int 的内容,这将抛出FormatException。如果您不确定用户是否会输入一个好的数字(我总是不这样做),请使用TryParse。示例如下

    int value;
    
    if (int.TryParse(Console.ReadLine(), out value))
        Console.WriteLine("parsed number as: {0}", value);
    else
        Console.WriteLine("incorrect number format");
    

    【讨论】:

      【解决方案2】:

      问题是 Console.Read() 返回一个 int,但 int.Parse 需要一个字符串。只需将其更改为

      int num =Console.Read();
      

      【讨论】:

      • 我已经这样做了,但是它返回的是 ASCII 数字而不是数字本身
      • @user2224223 在你的代码中用 Console.ReadLine() 替换 Console.Read()
      • 我不认为 OP 想要 ASCII 表示用户输入。此外,它只需要输入中的第一个char
      • It's better to use Console.ReadLine() 返回一个字符串,然后在代码中创建一个 int 变量,将控制台输入的字符串转换为整数
      【解决方案3】:

      Console.Read() 和 ASCII

      发生这种情况是因为Console.Read() 实际返回并且int,而不是string。它返回所按下键的 ASCII 码,您需要将其转换为 char,然后再转换为字符串,然后解析它。

      var val = int.Parse(((char)Console.Read()).ToString());
      

      请注意,Console.Read() 不会以您认为的格式返回整数,09 的值实际上在 6070 出现,因为它们是 关键代码 不是你按的字符。

      See the ASCII table here

      Console.ReadLine()

      另一种可能更好的解决方案是使用Console.ReadLine(),它返回string

      var val = int.Parse(Console.ReadLine());
      

      警告

      使用int.Parse() 时应始终小心,因为如果提供的字符串不是数字,它将引发异常。一个更好的选择是使用int.TryParse(),你给它一个out 参数,它会返回解析是否成功。

      string text = Console.ReadLine();
      int val;
      if (int.TryParse(text, out val))
      {
          // It is a number
      }
      {
          // It is not a number
      }
      

      【讨论】:

        【解决方案4】:

        你得到它的原因是因为 Console.Read 返回一个 int

        http://msdn.microsoft.com/en-us/library/system.console.read.aspx

        而且它不能解析int,只能解析字符串。

        您可能想要 Console.ReadLine - 它返回一个字符串。

        【讨论】:

          猜你喜欢
          • 2015-10-14
          • 2018-07-14
          • 2013-01-07
          • 2014-05-17
          • 1970-01-01
          • 1970-01-01
          • 2014-04-14
          • 2012-12-10
          相关资源
          最近更新 更多