1
public interface ICommandService
{
    void Handle(Command command);
    void RegisterHandler<T>(Action<T> handler);
}
public class CampaignCommandHandler
{ 
  .
  .
   .
   public void Handle(RegisterCampaignCommand command)
    {
          //Some code here
     }
   .
   .
}

目前像这样手动向处理程序注册命令。

commandService.RegisterHandler<RegisterCampaignCommand>(campaignCommandHandler.Handle);

我有很多命令,每个命令在 CampaignCommandHandler 类中都有一个句柄函数。

var handles = campaignCommandHandler.GetType().GetMethods().Where(x => x.Name == "Handle");

  foreach (var handle in handles)
   {
      var command = handle.GetParameters().FirstOrDefault(x => x.ParameterType.BaseType == typeof(Command));

        // This is something, I want to do, which is obviously not the right as is 
       commandService.RegisterHandler<command.GetType()>(GetActionfromMethodInfo(handle)); 

   }

我正在尝试执行上述操作,但不确定如何使用反射来完成。我想知道是否有人可以指导我。

谢谢。

4

1 回答 1

1

试试这个:

var methods = campaignCommandHandler.GetType().GetMethods().Where(x => x.Name == "Handle");
foreach(var method in methods)
{
    var parameter = method.GetParameters().FirstOrDefault(x => typeof(Command).IsAssignableFrom(x.ParameterType));
    if(parameter == null)
    {
        continue;
    }
    var commandType    = parameter.ParameterType;
    var handler        = method.CreateDelegate(typeof(Action<>).MakeGenericType(commandType), campaignCommandHandler);
    var registerMethod = commandService.GetType().GetMethod("RegisterHandler").MakeGenericMethod(commandType);

    registerMethod.Invoke(commandService, new object[] { handler });
}
于 2013-11-14T00:32:36.423 回答