How to instantiate an interface, with a generic parameter

时间:2015-10-06 00:27:03

标签: c# interface

I have some classes that implement the interface below:

ISearchBase<T>

But I don't know which class will be instantiated, so I let "the user decide", like the example below:

var objectResponse = Activator.CreateInstance(Type.GetType(ResponseNamespace));

The problem is: Each those classes has a return and I'm trying to use like this:

var object = (ISearchBase<objectResponse >)
          Activator.CreateInstance(Type.GetType(Namespace));

But the compiler won't let me do this... What can I do?

The error is:

The type or namespace name 'objectResponse' could not be found.

1 个答案:

答案 0 :(得分:1)

执行var object = (ISearchBase<X>)...时,必须在编译时知道类型Xvar关键字只是编译器推断类型的简写。因此,您无法使用运行时类型来解析X

您在创建object后未显示如何处理{{1}}。当然可以使用反射调用泛型方法来允许您输入类型安全的代码,但是如果没有看到更多代码,我无法判断它是否对您有用。