我无法理解在C#3.0中传递代理的规则是什么。最终.Max()
给出了如下所示的编译错误,但我无法理解该案例与其他案例之间的重大差异。
int NamedIdentity(int val) { return val; }
Func<int, int> Identity = x => x;
void Main() {
var range = Enumerable.Range(1, 10);
range.Max();
range.Max(x => x);
range.Max(Identity);
range.Max((Func<int, int>) NamedIdentity);
range.Max(new Func<int, int>(NamedIdentity));
// this line gives compile error
range.Max(NamedIdentity);
/* The call is ambiguous between the following methods or properties:
* 'System.Linq.Enumerable.Max<int>(System.Collections.Generic.IEnumerable<int>, System.Func<int,decimal>)' and
* 'System.Linq.Enumerable.Max<int>(System.Collections.Generic.IEnumerable<int>, System.Func<int,decimal?>)'
*/
}
为什么这不编译?我的理解是NamedIdentity
被声明为Func<int, int>
,因此它不需要被渲染,尽管显然我错了。一个线索是编译错误正在讨论Decimal
s,即使代码中的任何地方都没有引用。那个是从哪里来的?函数引用是否可以隐式转换为具有相同签名的委托?
答案 0 :(得分:3)