在我的代码中我有以下界面
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/