简体   繁体   English

C#有没有一种创建接受匿名函数代码作为参数的函数的方法?

[英]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. 已经内置了使用,foreach,for等功能,但我不知道是否可以创建类似的东西。 Is it? 是吗?

The reason why I ask this is because 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;
});

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

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