简体   繁体   English

FUNC <int,bool> Linq中没有return关键字?

[英]Func<int,bool> without return keyword in Linq?

While using Linq I stumbled upon the following expression: 使用Linq时我偶然发现了以下表达式:

bool biggerThan10Exists = numbers.Any(n => n > 10);

The definition for Any is as follows: Any的定义如下:

public static bool Any<TSource>(
    this IEnumerable<TSource> source,
    Func<TSource, bool> predicate
)

The definition for Func is as follows: Func的定义如下:

public delegate TResult Func<in T, out TResult>(
        T arg
)

So if Any requires a Func which requires delegates to be passed that returns an int, how comes I can pass a lambda expression that in my opinion is a definition of a void delegate, ie 因此,如果Any需要一个Func ,它需要传递一个返回 int的委托,那我怎么能传递一个lambda表达式,在我看来是一个void委托的定义,即

n => n > 10

While I would expect 虽然我期待

n => return n > 10

I'm pretty sure I'm obviously missing something here, but what? 我很确定我明显错过了什么,但是什么?

This type of lambda expression is called an expression lambda : 这种类型的lambda表达式称为表达式lambda

n => n > 10

In expression lambdas, what follows => must be an expression and the return type is inferred by the compiler. 在表达式lambdas中,以下内容=>必须是一个表达式,并且返回类型由编译器推断。 One of the consequences is that you cannot use expression lambda syntax to create a lambda with a void return type. 其中一个后果是您不能使用表达式lambda语法来创建具有void返回类型的lambda。

There is another syntax for lambdas, called statement lambda : lambda有另一种语法,称为语句lambda

n => { return n > 10; }

Here the => is followed by a block containing one or more statements; 这里=>后跟一个包含一个或多个语句的块; if you want to return a value you must do so explicitly, and it's also possible to have a void return type (don't return anything). 如果你想返回一个值,你必须明确地这样做,并且也可以有一个void返回类型(不要返回任何东西)。

Note that support for statement lambdas was only added in .NET 4.0, and in general is worse throughout the framework than that for expression lambdas, eg many (all?) LINQ query providers will refuse to work with statement lambdas even if they can be trivially written as the equivalent expression lambda. 请注意,语句lambdas的支持仅在.NET 4.0中添加,并且在整个框架中通常比表达式lambdas更糟糕,例如,许多(所有?)LINQ查询提供程序将拒绝使用语句lambdas,即使它们可以是简单的写作等效表达式lambda。

n > 10 is an expression that returns a boolean value. n > 10是一个返回布尔值的表达式。

So n => n > 10 means, take n and return true if it's bigger than 10, return false otherwise... 所以n => n > 10表示,取n并且如果它大于10则返回true,否则返回false ...

Also here the return is implicit. 这里的回报也是隐含的。 You can also write it like this: 你也可以像这样写:

n => { return n > 10; }

This is simply equivelant to: 这对于:

n => {   
         if (n > 10) 
              return true;
          return false;
     };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM