开发者

C# Is there a way to create functions that accept anonymous function code as argument?

I would like to do something like

NameOfTheMethod(parameters){
  // Code...
}

There's using, foreach, for, etc. that are already built-in, but I don't know if creating something similar is even possible. Is it?

The reason why I ask this is b开发者_开发知识库ecause sometimes that there are many different pieces of code that are wrapped by basically the same code (examples are opening a connection to the database, creating the command, settings the datareader, testing if an element exists in cache and, if not, go get it, otherwise get it from cache, etc.)


Yes, you can take a delegate instance as an argument:

void MyMethod(Func<Arg1Type, Arg2Type, ReturnType> worker) {
    Arg1Type val1 = something;
    Arg2Type val2 = somethingelse;
    ReturnType retVal = worker(something, somethingelse);
    // ...
}

You'd call it like:

MyMethod((arg1, arg2) => {
  // do something here with the arguments
  return result;
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜