Using one delegate to for several methods with different parameters

后端 未结 4 810
时光取名叫无心
时光取名叫无心 2021-01-20 19:22

Is it possible to use one delegate for several methods with different parameters somehow? I use reflection to get all the methods in a class, and I want to assign each of th

相关标签:
4条回答
  • 2021-01-20 19:43

    You could make a Dictionary<MyEnum, Object>;. After you extract the value, cast it to the appropriate delegate and invoke it.

    Alternately, you could use something like the command pattern, and pass in commands rather than enumerated values:

    interface ICommand
    {
        void Execute();
    }
    
    class SomeCommand : ICommand
    {
        public SomeCommand(/* instance and parameters go here */) { /* ... */ }
    
        public void Execute() { /* ... */ }
    }
    
    class SomeOtherCommand : ICommand { /* ... */ }
    

    If you want them to be accessible like an enum, you could make a factory class w/ static methods to create your specific commands:

    class RemoteCommand
    {
        public static SomeCommand SomeCommand
        {
            get
            {
                var result = new SomeCommand(/* ... */);
                // ...
                return result;
            }
        }
    
        public static SomeOtherCommand SomeOtherCommand { get { /* ... */ } }
    }
    

    Edit:

    Also, not sure of your needs, but exposing a list of method calls that the user might want to make, but abstracting out exactly what gets called sure sounds like an interface:

    interface IRemoteCommand
    {
        void RemoteMethod();
        void OtherRemoteMethod(/* params */);
        void ImplementedAgainstADifferentServerMethod();
    }
    
    0 讨论(0)
  • 2021-01-20 19:51

    If the parameter count, order and type are the same, yes.

    Simply put, a delegate is just a method signature.

    0 讨论(0)
  • 2021-01-20 19:52

    You can use the Delegate.CreateDelegate Function and pass the appropriate delegate Type (Action<> or Func<>) and an instance of the MethodInfo, in this case you should construct the delegate type according to the MethodInfo parameters.

    0 讨论(0)
  • 2021-01-20 19:54

    You'd need a uniform way of passing them parameters. That means you'd need to pass them an array of parameters. And that means you need a MethodInfo, not a delegate.

    Just store the MethodInfo against the name in the dictionary. Then when you need to call them, use the Invoke method to make the call, passing the target object and the array of parameters.

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