Delegate for any method type - C#

后端 未结 4 414
遥遥无期
遥遥无期 2021-01-01 18:07

I want to have a class that will execute any external method, like this:

class CrazyClass
{
  //other stuff

  public AnyReturnType Execute(AnyKindOfMethod M         


        
4条回答
  •  我在风中等你
    2021-01-01 18:55

    You can do this a different way by Func and closures:

    public T Execute(Func method)
    {
       // stuff
       return method();
    }
    

    The caller can then use closures to implement it:

    var result = yourClassInstance.Execute(() => SomeMethod(arg1, arg2, arg3));
    

    The advantage here is that you allow the compiler to do the hard work for you, and the method calls and return value are all type safe, provide intellisense, etc.

提交回复
热议问题