简体   繁体   English

如何使用泛型参数实例化接口

[英]How to instantiate an interface, with a generic parameter

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.找不到类型或命名空间名称“objectResponse”。

When you do var object = (ISearchBase<X>)... you must know the type X at compile time.当您执行var object = (ISearchBase<X>)...必须在编译时知道类型X The var keyword is just short-hand for the compiler to infer the type. var关键字只是编译器推断类型的简写。 So, you cannot use a run-time type to resolve for X .因此,您不能使用运行时类型来解析X

You haven't shown what you what to do with the object after you've created it.在创建object之后,您还没有展示如何处理它。 It is certainly possible to call a generic method using reflection to allow you to type-safe code, but I can't tell if that will be useful to you or not without seeing more code.当然可以使用反射调用泛型方法以允许您对代码进行类型安全,但是如果没有看到更多代码,我无法确定这对您是否有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM