Delegate for any method type - C#

后端 未结 4 384
遥遥无期
遥遥无期 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:38

    I think you are better off using reflections in this case, as you will get exactly what you asked for in the question - any method (static or instance), any parameters:

    public object Execute(MethodInfo mi, object instance = null, object[] parameters = null)
    {
        return mi.Invoke(instance, parameters);
    }
    

    It's System.Reflection.MethodInfo class.

    0 讨论(0)
  • 2021-01-01 18:46
    public static void AnyFuncExecutor(Action a)
    {
        try
        {
            a();
        }
        catch (Exception exception)
        {
            throw;
        }
    }
    
    0 讨论(0)
  • 2021-01-01 18:50

    Kinda depends on why you want to do this in the first place...I would do this using the Func generic so that the CrazyClass can still be ignorant of the parameters.

    class CrazyClass
    {
        //other stuff
    
        public T Execute<T>(Func<T> Method)
        {
            //more stuff
            return Method();//or something like that
        }
    
    
    }
    
    class Program
    {
        public static int Foo(int a, int b)
        {
            return a + b;
        }
        static void Main(string[] args)
        {
            CrazyClass cc = new CrazyClass();
            int someargs1 = 20;
            int someargs2 = 10;
            Func<int> method = new Func<int>(()=>Foo(someargs1,someargs2));
            cc.Execute(method);
            //which begs the question why the user wouldn't just do this:
            Foo(someargs1, someargs2);
        }
    }
    
    0 讨论(0)
  • 2021-01-01 18:55

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

    public T Execute<T>(Func<T> 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.

    0 讨论(0)
提交回复
热议问题