Cannot convert from method group to Int32

后端 未结 3 1823
孤城傲影
孤城傲影 2021-01-22 00:25

I want my small math program to look really sleek, and by this I mean under the Main method I have the following methods:

Greet()
UserInput1()
UserI         


        
相关标签:
3条回答
  • 2021-01-22 01:00

    Call the method like the following, So that the method result will be called with output from the firstNumber() and secondNumber() as well :

    result(firstNumber(),secondNumber());
    

    Few more suggestions:

    Make the method Greet() to a re-usable one by passing appropriate message and then display it. so that you can use the same for all display operations. the signature of the method will be:

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

    The method Convert.ToInt32() will convert the given input to an integer value only if the input is convertible. else it will throws FormatException. So i prefer you to use int.TryParse for this purpose. Which will help you to determine whether the conversion is success or not. so the Method signature for firstNumber() will be like the following:

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

    Hope that you will change the secondNumber() as well

    0 讨论(0)
  • 2021-01-22 01:08

    change this:

    result(firstNumber, secondNumber);
    

    to this:

    result(firstNumber(), secondNumber());
    

    and remove the calls to the 2 methods in the two lines above.

    To call a method without parameters, you need the parentheses without content.

    0 讨论(0)
  • 2021-01-22 01:25

    Cannot convert from method group to int

    This error message occurs when you attempt to take a method (without invocation) and pass it as a type. The result method is expecting two parameters of type int, but you're attempting to pass it the method, rather than the result of the method invocation.

    You need to store the results in a variable, or invoke the methods with the ():

    Like this:

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

    or this:

    static void Main(string[] args)
    {
        Greet();
        result(firstNumber(), secondNumber());
        Console.ReadKey(); 
    }
    
    0 讨论(0)
提交回复
热议问题