简体   繁体   中英

Cannot Convert from Method Group to Object - C#

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.

代码片段错误

Would be great if someone could highlight the problem here.

您需要select.Average() (带括号)。

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.

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

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);

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

with ( Parenthesis() )

这对我来说是一个粗心的错误,我试图像属性一样调用 Method 而不是像方法一样调用 Method()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM