Pass code to a method as an argument

妖精的绣舞 提交于 2019-12-23 20:25:22

问题


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
...

}

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.


回答1:


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; });

Or:

int MyFunc(string x)
{
    return 1;
}

Something(1,2 MyFunc);



回答2:


You could try the Template method pattern

Which basically states soemthing like this

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();
}

In a child class

class Child : Parent
{
   protected override void CustomWork()
   {
      // do you specialized work
   }
}



回答3:


You would use delegates to handle this. It would likely look something like:

void DoWork(string parameter1, string parameter2, Action<string,string> customCode)
{
    // ... Common code
    customCode(parameter1, parameter2);
    // ... Common code
    customCode(parameter1, parameter2);
    // ... Common code
}



回答4:


If the custom code doesn't have to interact with the common code, it's easy:

void DoWork(..., Action custom)
{
    ... Common Code ...
    custom();
    ... Common Code ...
}



回答5:


Assuming you need to use the two string parameters in the custom code, the following should get the job done. If you don't actually care about the results of the custom code, you can replace Func<string, string, TResult> with Action<string, string>. Additionally, if your custom code needs to process results from the common code above it, you can adjust the parameter types that your Func<> (or Action<>) takes in and then pass in the appropriate values.

void DoWork(string parameter1, string parameter2, Func<string, string, TResult> customCode) {
    //Common code 
    var customResult = customCode(parameter1, parameter2);
    //Common code 
}

Using Func<T, TResult>: http://msdn.microsoft.com/en-us/library/bb534960

Using Action<T>: http://msdn.microsoft.com/en-us/library/018hxwa8



来源:https://stackoverflow.com/questions/10903874/pass-code-to-a-method-as-an-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!