简体   繁体   English

如何从泛型类型调用重载方法

[英]How to call an overloaded method from generic type

I have defined a generic interface 我定义了一个通用接口

interface IHandler<in TCommand> where TCommand:Command
{
     void Handle(TCommand command);
} 

And the class 和班级

public class MyHandler:
    IHandler<CommandA>,
    IHandler<CommandB>,
    IHandler<CommandC>
{
    public void Handle(CommandA command)
    {...}

    public void Handle(CommandB command)
    {...}

    public void Handle(CommandC command)
    {...}
}

For some reasons, I need to call the handler dynamically, and the things I have is the IoC container, a handler's qualified name and the parameter instance (eg CommandB). 由于某些原因,我需要动态调用处理程序,而我所拥有的就是IoC容器,处理程序的限定名称和参数实例(例如CommandB)。 And my question is how can I invoke the Handle method? 我的问题是如何调用Handle方法?

public void DynamicCallHandleMethod(string typeName, Command command)
{
     Container container = new Container();
     container.Register<MyHandler>();

     object handler = container.Resolve(Type.GetType(typeName));
     //handler.Handle(command);  <---- How to make it?
}

Note, I know Reflection may be one of the solutions, so I hope there's another more elegant way, Thanks in advance. 注意,我知道反射可能是解决方案之一,所以我希望有另一种更优雅的方法,谢谢。

Implement a Method handling a Command value that calls the respective (they might even be private then) methods: 实现一个处理Command值的方法,该方法值调用相应的(然后它们甚至可能是私有的)方法:

public void Handle(Command command)
{
    if(command is CommandA comA)
        Handle(comA);
    else if(command is CommandB comB)
        Handle(comB);
    else if(command is CommandC comC)
        Handle(comC);
    else
        // Handle if necessary.
}

also casting the handler as an object on resolve will not expose the Interface. 同样,将处理程序强制转换为解析对象时,也不会公开接口。 Either you need var or implicilty IHandler as type. 您需要var或隐式IHandler作为类型。

Create a 'dynamic' variable and assign it with 'command', then pass this to the handle method. 创建一个“动态”变量,并为其分配“命令”,然后将其传递给handle方法。 This should resolve the type at runtime and select the appropriate method. 这应该在运行时解析类型并选择适当的方法。

dynamic cmd = command;
handler.Handle( cmd );

Alternatively, look into implementing the visitor pattern. 或者,研究实现访客模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM