创建通用实例 [英] Create Instance of Generic

查看:131
本文介绍了创建通用实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实现命令模式的WCF服务。使用反射,我创建了一个Dictionary,其中键是命令类型,值是CommandHandler。我们的想法是从WCF接收命令,使用字典获取处理程序类型,然后使用激活器创建处理程序的实例。

I have a WCF service that implements a command pattern. Using reflection, I've created a Dictionary where the key is the command type and the value is the CommandHandler. The idea is to receive the command from WCF, using the dictionary to get the handler type, then create an instance of the handler using the activator.

    public CommandResponse RunCommand(Command command)
    {
        _logger.Trace("Running Command");
        var handlerType = HandlerMap[command.GetType()];

        var handler = (AbstractCommandHandler<>)Activator.CreateInstance(handlerType);

        handler.HandleCommand(command);
        return new PostStatCommandResponse();

    }

public class StatCommandHandler : AbstractCommandHandler<PostStatCommand>
{

    public override void HandleCommand(PostStatCommand command)
    {

    }
}

问题是Activator.CreateInstance返回一个对象,而不是强类型的commandhandler。我需要能够调用HandleCommand,但不知道如何将其转换为AbstractCommandHandler<>

The problem is that Activator.CreateInstance returns an object, not a strongly typed commandhandler. I need to be able to call the HandleCommand, but can't figure out how to cast it to the base AbstractCommandHandler<>

// Syntax error.  Gotta provide type to generic
(AbstractCommandHandler<>)Activator.CreateInstance(handlerType);

// Casting error at run time
(AbstractCommandHandler<Command>)Activator.CreateInstance(handlerType);

// This is dumb and defeats the purpose.
(AbstractCommandHandler<PostStatCommand>)Activator.CreateInstance(handlerType);

帮助?

Help?

推荐答案

var handler = Activator.CreateInstance(handlerType);
handlerType.GetMethod("HandleCommand").Invoke(handler, new [] {command});






或者,创建一个非泛型基类一个接口也可以):


Or, create a non-generic base class (an interface will also do):

public abstract class AbstractCommandHandler
{
    public abstract void HandleCommand(Command command);
}

public abstract class AbstractCommandHandler<T> : AbstractCommandHandler
{
    public override void HandleCommand(Command command)
    {
        HandleCommand((T) command);
    }

    public abstract void HandleCommand(T command);
}

public class StatCommandHandler : AbstractCommandHandler<PostStatCommand>
{

    public override void HandleCommand(PostStatCommand command)
    {

    }
}

以及您的 RunCommand 方法:

var handler = Activator.CreateInstance(handlerType);
((AbstractCommandHandler)handler).HandleCommand(command);

这篇关于创建通用实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆