简体   繁体   English

无法从方法组转换为对象 - C#

[英]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.我试图熟悉 C# 并尝试了以下程序 - 它只输出数组中偶数的平均值。

代码片段错误

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() Missing Parenthesis ()是你错误的原因。它应该是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 .您不是在调用Average should be select.Average()应该是select.Average()

the problem is that, you forgot to include the parenthesis since Average is a method ( extension type ).问题是,您忘记包含括号,因为Average是一种方法(扩展类型)。 Another solution is to use lambda expression, something like this,另一种解决方案是使用 lambda 表达式,像这样,

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()这是一个扩展Method所以它应该是这样的: Average()

with ( Parenthesis() )与(括号())

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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