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.
答案 0 :(得分:1)
执行var object = (ISearchBase<X>)...
时,必须在编译时知道类型X
。 var
关键字只是编译器推断类型的简写。因此,您无法使用运行时类型来解析X
。
您在创建object
后未显示如何处理{{1}}。当然可以使用反射调用泛型方法来允许您输入类型安全的代码,但是如果没有看到更多代码,我无法判断它是否对您有用。