我有课MyClass<T>
哪里T
是一些接口(interface):
class MyClass<T> where T: IMyInterface
我编写了几个扩展 MyClass
的类使用IMyInterface
的一些实现,例如:
class MySecondClass : MyClass<MyInterfaceImplementation>
为什么分配MySecondClass
类型为 MyClass<IMyInterface>
的变量的实例不允许吗?
MyClass<IMyInterface> x = new MySecondClass()
当我添加隐式转换时:
public static implicit operator MyClass<IMyInterface>(MySecondClass c) {
return c;
}
它开始工作。
最佳答案
要执行您想要的操作,您应该使用 out
关键字声明类型参数 T
是协变的(请参阅 MSDN 上的 Covariance and Contravariance in Generics)。
您需要稍微修改一下代码,因为协变和逆变只能在接口(interface)上定义:
interface IMyInterface {
}
// note that this one is an interface now
interface IMyClass<out T> where T : IMyInterface {
}
class MyInterfaceImplementation : IMyInterface {
}
class MySecondClass : IMyClass<MyInterfaceImplementation> {
}
class Program {
static void Main(string[] args) {
IMyClass<IMyInterface> x = new MySecondClass();
}
}
关于c# - 从模板类转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19767117/