c# - 当 Activator 的接口(interface)具有泛型时,如何从 Activator 实例化一个对象?

标签 c# reflection activator

在我的代码中我有以下界面

public interface ILogParser<TParserOptions> { }

我已经通过反射检索到所有使用此接口(interface)的类型,并且正在尝试实例化它们。通常我会按照以下方式做一些事情:

var parser = (ILogParser)Activator.CreateInstance(parserType)

但是,当您处理泛型时,这不起作用,因为您需要在转换时知道泛型类型,这可能因每个实现的类型而异。

这可能吗?

最佳答案

您可以使用 Type.MakeGenericType在接口(interface)的类型上创建实现该接口(interface)的某个对象的特定实例。

一旦您拥有合适的类型(指定了通用类型),Activator.CreateInstance 将正常工作。

例如,在上面,你可以使用:

Type interfaceType = typeof(LogParser<>); // Some class that implements ILogParser<T>
// Make the appropriate type - 
// Note: if this is in a generic method, you can use typeof(T)
Type fullType = interfaceType.MakeGenericType( new[] { typeof(Int32) });

object result = Activator.CreateInstance(fullType);

关于c# - 当 Activator 的接口(interface)具有泛型时,如何从 Activator 实例化一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7493204/

相关文章:

c# - 创建泛型类型的实例

c# - Activator.CreateInstance 导致 nunit 锁定,从而阻止 visual studio 构建

ipod - MPMediaItem 更改属性

c# - 使用 Pdftron 在 C# 中将 Excel 转为 Pdf

c# - 使用 JOIN 的 ADO.NET 实体模型和 LINQ

c# - 确保延迟执行将只执行一次,否则

.net - 以整数开头的标识符

reflection - 获取Go结构体中字段的reflect.Ptr类型

reflection - Nancy 和抽象基模块类/创建幻像类实例

javascript - 希登菲尔德失去值(value)