“()=>”的目的是什么?在lambda c# [英] What is the purpose of "() =>" in lambda c#

查看:117
本文介绍了“()=>”的目的是什么?在lambda c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图弄清楚这一点,这真的让我失望。我有一些代码看起来像这样

I have been trying to figure this out and it's really bugging me. I have some code that looks like this

static T MyFunction<T>(Func<T> action, int i, int i2)
{
    ...some code here
}

当我需要调用这个代码,我试过这个

When I need to call this code I tried this

var result = MyFunction<List<string>>(MethodThatReturnsListofString(int number), 1,2)

它表示最好的重载有无效的参数失败
但是当我尝试以下

It fails stating that the best overload has invalid arguments But when I tried the following

var result = MyFunction<List<string>>(() => MethodThatReturnsListofString(int number), 1,2)

它工作正常。在这种情况下,()=>的功能是什么?我认为()不能与需要超过0个args的方法一起使用。

It works fine. What is the function of "() =>" in this case. I thought() could not be used with methods required more than 0 args.

推荐答案

MyFunction< T> 期望作为第一个参数没有参数并返回类型 T

MyFunction<T> expects as first parameter a method that takes no arguments and returns the type T.

首次尝试 MethodThatReturnsListofString(number)并尝试提供结果(一个 List< T> )作为参数,而不是一种方法。

In your first attempt, you call MethodThatReturnsListofString(number) and try to provide the result (a List<T>) as parameter instead of a method.

在您的第二次尝试中,您可以通过键入()=>创建具有所需签名的方法。 MethodThatReturnsListofString(number)并将其作为参数。

In your second try, you create a method with the required signature by typing () => MethodThatReturnsListofString(number) and provide this as parameter.

为了使之更清楚,你可能已经创建了一个方法,如

To make it more clear, you could have created a method like

static List<T> MyAnonymousMethod()
{
    return MethodThatReturnsListofString(number);
}

然后调用

MyFunction<List<string>>(MyAnonymousMethod, 1, 2);

使用()=> MethodThatReturnsListofString 您声明一个匿名方法内联,因此您不需要首先创建 MyAnonymousMethod 。这部分代码是所谓的 lambda表达式

With () => MethodThatReturnsListofString you declare an anonymous method inline and so you don't need to create MyAnonymousMethod first. This part of your code is what is called a lambda expression.

注意通过声明此lambda, MethodThatReturnsListofString 不会立即执行!只有当 MyFunction 真的会调用此操作参数,如

Note that by declaring this lambda, MethodThatReturnsListofString is not executed immediatly! It will be executed only when MyFunction really calls this action parameter like

static T MyFunction<T>(Func<T> action, int i, int i2)
{
    // ... some code
    var result = action();
    // ... more code
}

这篇关于“()=&gt;”的目的是什么?在lambda c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆