<分区>
Possible Duplicate:
Why is Func<T> ambiguous with Func<IEnumerable<T>>?
我注意到泛型有一个非常奇怪的重载解析问题...
考虑以下方法:
static void Foo<TSource>(TSource element, Func<TSource, int> selector)
{
"int".Dump();
}
static void Foo<TSource>(TSource element, Func<TSource, double> selector)
{
"double".Dump();
}
static T Identity<T>(T value)
{
return value;
}
(C# 4,在 LINQPad 中测试)
如果我尝试调用 Foo
使用 lambda 表达式作为选择器,一切正常:
Foo(42, x => x); // prints "int"
但是如果我替换 x => x
与 Identity
, 编译器无法在 2 Foo
之间做出决定重载:
Foo(42, Identity);
// The call is ambiguous between the following methods or properties:
// 'UserQuery.Foo<int>(int, System.Func<int,int>)' and
// 'UserQuery.Foo<int>(int, System.Func<int,double>)'
第二个重载如何成为有效候选者?类型推断正确地确定了 TSource
是int
, 所以 T
Identity
的参数方法必须是 int
同样,所以返回类型必须是 int
太... Identity
可能是 Func<int,int>
或 Func<double,double>
, 但不是 Func<int,double>
!
而且情况变得更糟!即使我明确指定了所有类型参数,我仍然会得到同样的错误:
Foo<int>(42, Identity<int>); // The call is ambiguous...
这里怎么会有歧义呢?据我所知,没有办法使用 Func<int,double>
的重载。可以是候选人。我猜解释一定在规范中的某处,但我找不到相关位...或者它可能是编译器中的错误,但我想这不太可能。
请注意,如果我显式创建委托(delegate),它确实有效:
Foo(42, new Func<int, int>(Identity)); // prints "int"
那么,有人可以解释一下这里发生了什么吗?另外,为什么它适用于 lambda 但不适用于方法组?