How can I design a class to receive a delegate having an unknown number of parameters?

前端 未结 6 1136
耶瑟儿~
耶瑟儿~ 2020-12-10 19:55

I continuously find myself having to write timed windows services that poll outside queues or run timed processes. I consequently have a fairly robust template by which to

6条回答
  •  春和景丽
    2020-12-10 20:02

    If your method parameter or property for the delegate is just of type Delegate you can use it's DynamicInvoke method to call the delegate, no matter what it's signature is. Like so:

    public void CallDelegate(Delegate del) {
      result = del.DynamicInvoke(1, 2, 3, 'A', 'B', 'C');
    }
    

    You really should be able to use a strong typed delegate, probably an Func or Action that can take whatever parameters you need to pass to the proccess.

    public void CallDelegate(Func del) {
      result = del(1, 2, 'A', 'B');
    }
    

    Personally, I would create an interface that all of the processes had to implement, then have the service discover all of the objects that implement it. That way they could provide their timing needs and a strongly typed method to call to the service. Something like this:

    //The interface
    interface ITimerProcess {
      TimeSpan Period {get;}
      void PerformAction(string someInfo);
    }
    
    //A process
    class SayHelloProcess : ITimerProcess {
    
      public TimeSpan Period { get { return TimeSpan.FromHours(1); } }
    
      public void PerformAction(string someInfo) {
        Console.WriteLine("Hello, {0}!", someInfo);
      }
    }
    

    For brievity I'll end it there, your service could descover all the process by looking for classes that implement ITimerProcess, then creating a timer for each based on the Period property each exposes. The timer would just have to call PerformAction with any other extra data you would like to pass.

提交回复
热议问题