使用 Activator 创建具有多个构造函数的类实例的最佳方法?
我已经实现了一个“插件”系统,其中我的应用程序创建了在运行时实现接口的类,以允许可插入功能。
我通过在插件程序集中实现指定接口的所有类上使用 Activator.CreateInstance 来实现此目的。
目前,我只使用该类的一种实现,并且为此我有两个构造函数参数,并将它们包含在 Activator.CreateInstance 调用中:
instanceList.Add((Foo)Activator.CreateInstance(_TypeList[typeKey], new object[] { arg1, arg2 }));
我意识到,如果添加不使用的实现,这可能会在以后引起问题这个构造函数签名。 处理这个问题的最佳情况是什么?
通过文档明确指出构造函数需要使用此签名,然后将其包含在 try/catch 中?
或者是否有一种方法可以调用类具有的任何构造函数? 记住我必须以某种方式匹配构造函数参数。
或者...通过将参数作为静态属性放入静态类中来避免构造函数参数?
I have implemented a 'plugin' system where my application creates classes that implement an interface at runtime to allow pluggable functionality.
I am achieving this by using Activator.CreateInstance on all classes that implement the specified interface within the plugin assembly.
At the current time I am only using one implementation of the class, and for it I have two constructor arguments, and have included those in the Activator.CreateInstance call:
instanceList.Add((Foo)Activator.CreateInstance(_TypeList[typeKey], new object[] { arg1, arg2 }));
I realise this may cause problems later if an implementation is added that does not use this constructor signature. What is the best situation to handle this.
Explicitly say via documentation that constructors need to use this signature, and then surround it in a try/catch?
Or would there be a way to invoke whatever constructor a class has? bearing in mind I would have to match up constructor arguments somehow.
Or... avoiding constructor arguments by putting the arguments in a static class as static propertys?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,我将重构代码以将构造抽象为工厂类。 然后工厂使用的策略可以决定最好的方法(如果不同)以及在出现错误(例如缺少构造函数)时该怎么做。 您可以使用泛型根据需要使接口具有强类型或松类型。
不过我还是会坚持使用 Activator。 我们已经在这种构造上做了很多工作,它给我们带来了很多东西,包括基于运行时发现的类型的后期绑定、单例、类型别名、自定义安全性等。
Firstly I would refactor the code to abstract the construction to say a factory class. Then the strategy used by the factory can decide the best way (if differing) and what to do in case of errors - such as missing constructor. You can use generics to make the interfaces as strongly or loosely typed as you need.
I'd stick with Activator though. We've done a lot of work with this kind of construction and its bought us a lot of things including late binding based on types discovered at runtime, singleton, type aliasing, custom security etc.
我要求所有插件都有一个不带参数的构造函数,并向接口添加一个带有一些通用参数的初始化方法。
无法知道插件的所有可能实现都需要哪些参数。
I would require all plug-ins to have a constructor without parameters and add an initialize method to the interface, with some general arguments.
There is no way to know which arguments all possible implemetations of the plug-in require.