在C#中传入匿名方法/函数作为参数

Jer*_*ose 2 c# anonymous-methods anonymous-function

我有一个方法需要有条件地执行一个方法,如下所示:

int MyMethod(Func<int> someFunction)
{
    if (_someConditionIsTrue)
    {
        return someFunction;
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我希望能够将Linq查询作为someFunction传递给MyMethod:

int i = MyMethod(_respository.Where(u => u.Id == 1).Select(u => u.OtherId));
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢?

Las*_*olt 6

int i = MyMethod(() => _respository.Where(u => u.Id == 1).Select(u => u.OtherId));
Run Code Online (Sandbox Code Playgroud)

如您所见,我已将查询转换为lambda.您将不得不这样做,因为否则,您的查询将在调用之前执行MyMethod(...并将引入编译时错误;))而不是在执行时执行.

附注:

return someFunction;应该是return someFunction();.