简体   繁体   English

如何使用反射和抽象对象动态加载类?

[英]How to use reflection and abstract objects to dynamically load classes?

I'm building a protocol handler. 我正在构建一个协议处理程序。 The protocol may support an unknown set of request types, and I will have a single class that implements each request type. 该协议可能支持一组未知的请求类型,我将有一个实现每种请求类型的类。 These request handler classes will extend a base handler class. 这些请求处理程序类将扩展基本处理程序类。 I'm trying to build the system such that in order to support a new request type, all I need to do is add a class for that and recompile/deploy/restart the service. 我正在尝试构建系统,以便为了支持新的请求类型,我需要做的就是为此添加一个类并重新编译/部署/重新启动服务。

So I have something like this: 所以我有这样的事情:

foreach (Type classType in protocolAssembly.GetTypes())
{
    if (classType.BaseType == typeof(ProtocolRequestHandler))
    {
        if (supportedRequestsMap.Contains(classType.Method))
        {
            // error: that method is already implemented!
        }

        supportedRequestsMap.Add(classType.Method, typeof(classType));
    }
}

Adding a new class is picked up when the service restarts, as long as the request method it handles is declared. 只要声明了它处理的请求方法,就会在服务重新启动时选择添加新类

How can I enforce at compile time through through the base class ProtocolRequestHandler that property Method will be implemented? 如何通过基类ProtocolRequestHandler在编译时强制执行属性Method I don't want to use a method type as "Null" or "Unknown", or throw exceptions, and I don't want to specify the supported protocol request type inherently in the name of the extending classes (I would like to call the classes whatever I like). 我不想使用方法类型为“Null”或“Unknown”,或抛出异常,我不想在扩展类的名称中固有地指定支持的协议请求类型(我想调用我喜欢的课程。

Is there some way I can enforce that a property has its value set in an inheriting class? 有什么方法可以强制一个属性在继承类中设置其值?

Is there a cleaner way I can do this kind of dynamic loading? 有没有更清洁的方式我可以做这种动态加载? Should I be using attributes to determine the supported method of the inheriting class? 我应该使用属性来确定继承类的受支持方法吗?

You should rely on interfaces as a contract of what methods that should be implemented by your plugins. 您应该依赖接口作为插件应该实现的方法的契约。
A (little old, but still very relevant) nice tutorial can be found on here 这里可以找到一个(有点旧,但仍然非常相关)很好的教程

If you are using a base class, why don't you just create your required method as an abstract method (or virtual and specify a default implementation if possible). 如果您使用的是基类,为什么不将所需的方法创建为抽象方法(如果可能,则为虚拟并指定默认实现)。 This will ensure that the method exists in your inherited class. 这将确保您的继承类中存在该方法。 I believe you probably already know this if you are into reflection and writing your own protocol handler, but am not sure there is a better way to get what you want. 我相信如果您正在反思并编写自己的协议处理程序,您可能已经知道了这一点,但我不确定是否有更好的方法来获得您想要的内容。

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

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