开发者

Passing in an anonymous method/function as a parameter in C#

开发者 https://www.devze.com 2023-03-01 22:30 出处:网络
I have a method that needs to conditionally execute a method, something like this: int MyMethod(Func<int> someFunction)

I have a method that needs to conditionally execute a method, something like this:

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

    return 0;
}

I want to be able to pass a Linq query in to MyMethod as someFunction:

int i = MyMethod(_respository.Where(u => u.Id == 1).Select(u => u.Ot开发者_JS百科herId));

How do I do this?


int i = MyMethod(() => _respository.Where(u => u.Id == 1).Select(u => u.OtherId));

As you can see, I've made the query into a lambda. You will have to do this because otherwise, your query will be executed just before calling MyMethod (...and will introduce compile-time errors ;) ) and not while it executes.

A side note:

This return someFunction; should be return someFunction();.


Maybe it's a typo, but in MyMethod you need to actually call the function:

        return someFunction();

And when calling it, you're calling the function directly. Instead you need to pass a lambda expression. Also, you seem to be passing in a Func<IEnumerable<int>>; add Single(), SingleOrDefault(), First() or FirstOrDefault():

int i = MyMethod(() => _respository.Where(u => u.Id == 1).Select(u => u.OtherId).SingleOrDefault());
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号