Cannot Convert from Method Group to Object - C#

前端 未结 6 1882
野趣味
野趣味 2021-01-12 03:23

I am trying to get familiar with C# and tried out the following program - it just outputs the average of the even numbers in the Array.

相关标签:
6条回答
  • 2021-01-12 03:42

    You need select.Average() (with the parens).

    0 讨论(0)
  • 2021-01-12 03:49

    This was a careless mistake on my part, I was trying to call Method like a property instead of Method() like a method

    0 讨论(0)
  • 2021-01-12 03:51

    You are not calling Average. should be select.Average()

    0 讨论(0)
  • 2021-01-12 03:53

    The Missing Parenthesis () is the reason for your error.It should be Average()

    without a Parenthesis,it is understood as a method group.The average method could have multiple overloads and it is unclear which specific overloaded method needs to be invoked.But when you mention the parenthesis it makes the intention clearer and the method gets called.

    0 讨论(0)
  • 2021-01-12 03:59

    It's an Extension Method so it should be like this: Average()

    with ( Parenthesis() )

    0 讨论(0)
  • 2021-01-12 04:02

    the problem is that, you forgot to include the parenthesis since Average is a method (extension type). Another solution is to use lambda expression, something like this,

    var numbers = new[] { 1, 2, 3, 4, 5 };
    Console.WriteLine(numbers.Where(x => (x % 2) == 0).Average());
    

    or

    var numbers = new[] { 1, 2, 3, 4, 5 };
    var select = (from num in numbers where (num % 2) == 0 select num).Average();
    Console.WriteLine(select);
    
    0 讨论(0)
提交回复
热议问题