问题描述
我尝试在 C# 中编译以下代码:
I try to compile the following code in C#:
public static T FirstEffective(IEnumerable<T> list)
{
Predicate<T> pred = x => x != null;
return Enumerable.FirstOrDefault(list, pred);
}
编译器 (Mono/.NET 4.0) 给出以下错误:
The compiler (Mono/.NET 4.0) gives the following error:
File.cs(139,47) The best overloaded method match for `System.Linq.Enumerable.FirstOrDefault<T>(this System.Collections.Generic.IEnumerable<T>,System.Func<T,bool>)' has some invalid arguments
/usr/lib/mono/4.0/System.Core.dll (Location of the symbol related to previous error)
File.cs(139,47): error CS1503: Argument `#2' cannot convert `System.Predicate<T>' expression to type `System.Func<T,bool>'
这很奇怪,因为 Predicate<T>
实际上是一个将参数 T
作为输入并返回 bool
的函数(T
甚至是协变的",因此允许 T
的特化).代表是否没有考虑Liskov Substitution 原则"来推导出 Predicate
等价于 Func
This is rather strange since a Predicate<T>
is in fact a function that takes as input a parameter T
and returns a bool
(T
is even "covariant" thus a specialization of T
is allowed). Do delegates do not take the "Liskov Substitution principle" into account to derive that Predicate<T>
is equivalent to Func<T,bool>
? As far as I know this equivalence problem should be decidable.
推荐答案
C# 规范明确了这一点:
C# specification is clear about that:
15.1 委托声明
C# 中的委托类型是名称等价的,而不是结构上等价的.具体来说,两种不同的委托类型具有相同的参数列表和返回类型被认为是不同的委托类型.
Delegate types in C# are name equivalent, not structurally equivalent. Specifically, two different delegate types that have the same parameter lists and return type are considered different delegate types.
这就是您的代码无法编译的原因.
That's why your code doesn't compile.
您可以通过调用委托而不是传递它来使其工作:
You can make it work by calling the delegate, instead of passing it:
public static T FirstEffective (IEnumerable<T> list) {
Predicate<T> pred = x => x != null;
return Enumerable.FirstOrDefault (list, x => pred(x));
}
更新
Eric Lippert 有一篇很棒的博文:前微软 C# 团队成员,详细回答了你的问题:代表和结构身份.
There is a great blog post by Eric Lippert: former member of C# Team as Microsoft, which answers your question in much details: Delegates and structural identity.
这篇关于为什么“谓词<T>"与“Func<T,bool>"不匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!