当对象的接口具有泛型时,如何从激活器实例化对象?
在我的代码中,我有以下接口,
public interface ILogParser<TParserOptions> { }
我已经通过反射检索了使用此接口的所有类型,并且我正在尝试实例化它们。通常我会做一些类似的事情:
var parser = (ILogParser)Activator.CreateInstance(parserType)
但是,当您处理泛型时,这不起作用,因为您需要在转换时知道泛型类型,这可能会根据每个实现的类型而有所不同。
这可能吗?
In my code I have the following interface
public interface ILogParser<TParserOptions> { }
I have retrieved all types that use this interface via reflection and I am trying to instantiate them. Normally I would do something along the lines of:
var parser = (ILogParser)Activator.CreateInstance(parserType)
However, this doesn't work when you are dealing with Generics, since you need to know the generic type at the time of casting, which can vary depending on each implemented type.
Is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在接口类型上使用 Type.MakeGenericType 来创建实现该接口的某个对象的特定实例。
一旦您拥有适当的类型(指定了泛型类型),
Activator.CreateInstance
就会正常工作。例如,在上面,您可以使用:
You can use Type.MakeGenericType on the interface's type to make a specific instance of some object that implements the interface.
Once you have the appropriate type (with the generic type specified),
Activator.CreateInstance
will work fine.For example, in the above, you could use: