无法将方法组转换为Int32。

4
我希望我的小型数学程序看起来非常流畅,也就是说,在Main方法下,我有以下方法:
Greet()
UserInput1()
UserInput2()
Result()

Greet() 中,我只是简单地打招呼“HI”,在 UserInput1() 中,我想收集第一个数字,在 UserInput2() 中,我想收集第二个数字,并在 Result() 中打印出 UserInput1 + UserInput2 的结果。我可以在 UserInput1 和 2 中收集数字,但是似乎无法将它们发送到 Result() ,除非在 Main() 函数下为它们分配值。
namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Greet();
            firstNumber();
            secondNumber();
            result(firstNumber, secondNumber);
            Console.ReadKey();
        }

        public static void Greet()
        {
            Console.WriteLine("Hello, pls insert two numbers");
        }

        public static int firstNumber()
        {
            int num01 = Convert.ToInt32(Console.ReadLine());
            return num01;
        }

        public static int secondNumber()
        {
            int num02 = Convert.ToInt32(Console.ReadLine());
            return num02;
        }

        public static void result( int num01, int num02)
        {

            Console.WriteLine(num01 + num02);
        }
    }
}
3个回答

9

改为:

result(firstNumber, secondNumber);

转换为:

result(firstNumber(), secondNumber());

并且删除上面两行中的两个方法调用。

如果要调用一个没有参数的方法,需要使用没有内容的括号。


2

无法将方法组转换为 int

当您试图将一个方法(未进行调用)作为类型传递时,就会出现此错误消息。方法result需要两个类型为int的参数,但是您试图传递方法本身而不是方法调用的结果。

您需要将结果存储在变量中,或使用()调用这些方法:

像这样:

static void Main(string[] args)
{
    Greet();
    var first = firstNumber();
    var second = secondNumber();
    result(first , second );
    Console.ReadKey(); 
}

或者这样:
static void Main(string[] args)
{
    Greet();
    result(firstNumber(), secondNumber());
    Console.ReadKey(); 
}

0
请按照以下方式调用该方法,以便使用firstNumber()secondNumber()的输出来调用该方法结果:
result(firstNumber(),secondNumber());

进一步的建议:

通过传递适当的消息并显示它,将方法Greet()变为可重用的方法。这样,您可以在所有显示操作中使用相同的方法。该方法的签名将是:

public static void Greet(string message)
{
    Console.WriteLine(message);
}

Convert.ToInt32() 方法只有在输入可转换时才会将其转换为整数值,否则它会抛出 FormatException 异常。因此,我建议您使用 int.TryParse 来实现此目的。这将帮助您确定转换是否成功。因此,firstNumber() 方法的签名将如下所示:

public static int firstNumber()
{
  int num01=0;
  if(!int.TryParse(Console.ReadLine(),out num01))
  {
    Greet("Invalid input");
  }
  return num01;
}

希望你也能修改secondNumber()函数。

感谢Flat Eric和David Pine,真是太有帮助了。运气不好的人。真的非常感激。:)) - Jason Vermaak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接