Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 当激活器的接口具有泛型时,如何从激活器实例化对象?_C#_Reflection_Activator - Fatal编程技术网

C# 当激活器的接口具有泛型时,如何从激活器实例化对象?

C# 当激活器的接口具有泛型时,如何从激活器实例化对象?,c#,reflection,activator,C#,Reflection,Activator,在我的代码中,我有以下接口 public interface ILogParser<TParserOptions> { } 但是,当您处理泛型时,这不起作用,因为您需要在强制转换时知道泛型类型,这取决于每个实现的类型 这是可能的吗?您可以在接口的类型上使用来创建实现接口的某个对象的特定实例 一旦有了适当的类型(指定了泛型类型),Activator.CreateInstance将正常工作 例如,在上面的示例中,您可以使用: Type interfaceType = typeof(Lo

在我的代码中,我有以下接口

public interface ILogParser<TParserOptions> { }
但是,当您处理泛型时,这不起作用,因为您需要在强制转换时知道泛型类型,这取决于每个实现的类型

这是可能的吗?

您可以在接口的类型上使用来创建实现接口的某个对象的特定实例

一旦有了适当的类型(指定了泛型类型),
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);
Type interfaceType=typeof(LogParser);//实现ILogParser的某个类
//制作适当的类型-
//注意:如果这是在泛型方法中,则可以使用typeof(T)
Type fullType=interfaceType.MakeGenericType(新[]{typeof(Int32)});
对象结果=Activator.CreateInstance(fullType);

问题的可能重复之处在于,我无法访问
IParser
方法,即使是非泛型方法。可能泛型不适合这种情况。我不知道编译时的类型。用户选择要使用的解析引擎,系统创建该引擎并继续解析。我希望我可以使用泛型类型的子类并使用它来传递特定于实现的选项,但看起来泛型无法实现这一点。
ILogParser
是一个接口——显然无法实例化它,不管它是否通过
MakeGenericType
@KallDrexx输入:您需要知道具体的类型。像MEF这样的东西在这里能帮上不少忙,不过…哦哦哦,我没想到MEF。我一直想找一个好的借口来学习它,也许就是这个。谢谢:)
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);