为什么“谓词<T>"与“Func<T,bool>"不匹配?

Why a `Predicatelt;Tgt;` doesn#39;t match a `Funclt;T,boolgt;`?(为什么“谓词lt;Tgt;与“Funclt;T,boolgt;不匹配?)
本文介绍了为什么“谓词<T>"与“Func<T,bool>"不匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在 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.

这篇关于为什么“谓词&lt;T&gt;"与“Func&lt;T,bool&gt;"不匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)