Lambda在FindAll中工作,但在将其用作Func(或Expression)时不起作用 [英] Lambda works in FindAll, but not when using it as an Func (or Expression)
问题描述
以下代码将无法编译:
Func<Person, bool> theLambda = (p) => p.Year >= 1992;
foreach (Person pers in PersonList.FindAll(theLambda))
{
Console.WriteLine(pers.Name);
}
public class Person
{
public string Name { get; set; }
public int Year { get; set; }
public Person(string Name, int Year )
{
this.Name = Name; this.Year = Year;
}
}
但是,如果我直接替换变量theLambda lambda,那么它的工作原理很好。这里发生了什么? (温柔,我是新手)。谢谢你提前!
(1)我读错了消息,但对我来说并不意味着什么。
(2)是的,我可以让它工作通过使用 compile()关键字的谓词,但这不是问题。
However, if I replace variable "theLambda" directly with the lambda, then it works just fine. What's going on here? (Be gentle, I'm a novice). Thank you so much in advance!
(1) I read the error message, but it doesn't mean anything to me.
(2) Yes, I can make it work with a Predicate by using the compile() keyword, but that's not the issue here.
编辑:为什么会有人降低这个?这个问题根本不是那么糟糕,因为问题领域确实不是逻辑性的。真正的人。
推荐答案
它的工作原理是因为如果你声明了lambda内联,编译器会隐式分配它的正确类型,即谓词< Person>
。您不必明确地告诉编译器的lambda类型,因为它已经知道它应该需要一个 Person
并返回一个 bool
如果您在列表< Person>
上调用 FindAll
。
It works because if you declare the lambda inline the compiler implicitly assigns it the right type, i.e. Predicate<Person>
. You don't have to explicitly tell the compiler the lambda type as it knows already that it should take a Person
and return a bool
if you call FindAll
on a List<Person>
.
foreach (Person pers in PersonList.FindAll(p => p.Year >= 1992))
{
Console.WriteLine(pers.Name);
}
您还可以使用 Enumerable.Where
- 具有相同功能的LINQ方法使其更易读:
You can also use Enumerable.Where
- LINQ method with the same functionality to make it a bit more readable:
foreach (Person pers in PersonList.Where(p => p.Year >= 1992))
{
Console.WriteLine(pers.Name);
}
从 msdn :
在写lambdas时,您通常不必为
输入参数指定类型,因为编译器可以基于
lambda主体,参数的委托类型以及其他因素来推断类型,如
C#语言规范。对于大多数标准的
查询运算符,第一个输入是
源序列中元素的类型。因此,如果您要查询IEnumerable< Customer>
,则
推断输入变量为客户
对象
令人困惑的部分是一个 Predicate
在逻辑上是一个 Func
,它接受某种类型的对象 T
并返回一个 bool
但是由于某些原因,这种打字不起作用,您必须使用 Predicate< T>
。在内部声明lambda函数避免了这种混淆,因为您只需编写lambda体,并让编译器自己推断该类型。
The confusing part is that a Predicate
is logically a Func
that takes an object of some type T
and returns a bool
, but for some reason this typing doesn't work and you have to use Predicate<T>
. Declaring the lambda function inline avoids this confusion as you just write the lambda body and let the compiler infer the type on its own.
这篇关于Lambda在FindAll中工作,但在将其用作Func(或Expression)时不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!