无法从方法组转换为对象 - C#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13116004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot Convert from Method Group to Object - C#
提问by Hari
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.
如果有人可以在这里突出问题,那就太好了。
采纳答案by Andrew Cooper
You need select.Average()(with the parens).
你需要select.Average()(带括号)。
回答by Pencho Ilchev
You are not calling Average. should be select.Average()
你不是在打电话Average。应该select.Average()
回答by Prabhu Murthy
The Missing Parenthesis ()is the reason for your error.It should be Average()
缺少括号()是您错误的原因。它应该是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.
没有括号,理解为一个方法组。一般的方法可以有多个重载,不清楚需要调用哪个特定的重载方法。但是当你提到括号时,它使意图更清晰,方法被调用。
回答by John Woo
the problem is that, you forgot to include the parenthesis since Averageis a method (extension type). Another solution is to use lambda expression, something like this,
问题是,您忘记包含括号,因为它Average是一种方法(扩展类型)。另一种解决方案是使用 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);
回答by Vishal Suthar
It's an Extension Methodso it should be like this: Average()
这是一个扩展,Method所以它应该是这样的:Average()
with ( Parenthesis() )
与(括号())

