[英]Pass code to a method as an argument
我有一个方法列表,几乎完全相同,除了一些差异:
void DoWork(string parameter1, string parameter2)
{
//Common code
...
//Custom code
...
//Common code
...
}
我想通过从另一个方法传递自定义代码来重用公共代码来简化解决方案。
我假设我必须使用带参数的动作来完成此任务,但无法弄清楚如何。
您可以尝试模板方法模式
这基本上就是这样的东西
abstract class Parent
{
public virtual void DoWork(...common arguments...)
{
// ...common flow
this.CustomWork();
// ...more common flow
}
// the Customwork method must be overridden
protected abstract void CustomWork();
}
在一个儿童班
class Child : Parent
{
protected override void CustomWork()
{
// do you specialized work
}
}
您将使用委托来处理此问题。 它可能看起来像:
void DoWork(string parameter1, string parameter2, Action<string,string> customCode)
{
// ... Common code
customCode(parameter1, parameter2);
// ... Common code
customCode(parameter1, parameter2);
// ... Common code
}
如果自定义代码不必与公共代码交互,那么很容易:
void DoWork(..., Action custom)
{
... Common Code ...
custom();
... Common Code ...
}
假设您需要在自定义代码中使用两个字符串参数,以下内容应该完成工作。 如果您实际上并不关心自定义代码的结果,可以使用Action<string, string>
替换Func<string, string, TResult>
Action<string, string>
。 此外,如果您的自定义代码需要处理其上方公共代码的结果,您可以调整Func <>(或Action <>)所接受的参数类型,然后传入适当的值。
void DoWork(string parameter1, string parameter2, Func<string, string, TResult> customCode) {
//Common code
var customResult = customCode(parameter1, parameter2);
//Common code
}
使用Func<T, TResult>
: http : //msdn.microsoft.com/en-us/library/bb534960
使用Action<T>
: http : //msdn.microsoft.com/en-us/library/018hxwa8
其他答案很棒,但您可能需要从自定义代码返回一些内容,因此您需要使用Func。
void Something(int p1, int p2, Func<string, int> fn)
{
var num = p1 + p2 + fn("whatever");
// . . .
}
像这样称呼它:
Something(1,2, x => { ...; return 1; });
要么:
int MyFunc(string x)
{
return 1;
}
Something(1,2 MyFunc);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.