传递code的方法作为参数 [英] Pass code to a method as an argument

查看:136
本文介绍了传递code的方法作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有说做pretty的类似的事情,但有一些区别的方法列表:

I have a list of methods that do pretty much the same thing, except a few differences:

void DoWork(string parameter1, string parameter2)

{

//Common code
...

//Custom code
...

//Common code
...

}

我想简化的解决方案,通过其他方法传递自定义code重用共同code。

I want to streamline the solution with reusing the common code by passing custom code from another method.

我想我必须使用带参数来完成这个动作,但无法弄清楚如何。

I assume I have to use an action with parameters to accomplish this, but can't figure out how.

推荐答案

其他答案是伟大的,但你可能需要从自定义code返回的东西,所以你需要使用Func键代替。

The other answers are great, but you may need to return something from the custom code, so you would need to use Func instead.

void Something(int p1, int p2, Func<string, int> fn)
{
   var num = p1 + p2 + fn("whatever");
   // . . .
}

这样称呼它:

Call it like this:

Something(1,2, x => { ...; return 1; });

或者

int MyFunc(string x)
{
    return 1;
}

Something(1,2 MyFunc);

这篇关于传递code的方法作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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