这个问题让我困惑不已,所以我想在这里问一下,希望有C#大神可以向我解释。
为什么这段代码会生成一个错误?
class Program
{
static void Main(string[] args)
{
Foo(X); // the error is on this line
}
static String X() { return "Test"; }
static void Foo(Func<IEnumerable<String>> x) { }
static void Foo(Func<String> x) { }
}
这个错误:
Error
1
The call is ambiguous between the following methods or properties:
'ConsoleApplication1.Program.Foo(System.Func<System.Collections.Generic.IEnumerable<string>>)' and 'ConsoleApplication1.Program.Foo(System.Func<string>)'
C:\Users\mabster\AppData\Local\Temporary Projects\ConsoleApplication1\Program.cs
12
13
ConsoleApplication1
无论我使用哪种类型 - 如果您在该代码中将"String"声明替换为"int",您将获得同样的错误。就像编译器无法区分 Func<T>
和 Func<IEnumerable<T>>
之间的区别一样。请问有人能解释一下吗?