[英]Generic type parameter is an class that implements an interface
Suppose we have a class that implements an interface 假设我们有一个实现接口的类
class MyParaClass : IMyParaInterface
And another class named MyObject which takes generic T 还有另一个名为MyObject的类,它使用通用T
class MyObject<T> where T: IMyParaInterface
Now I have a method that accepts this parameter 现在我有一个接受此参数的方法
Print(MyObject<IMyParaInterface> parameter)
When I get an object which type is MyObject<MyParaClass>
, and try to pass this to Print
method,Build fails because it can not convert MyObject<MyParaClass>
to MyObject<IMyParaInterface>
当我得到类型为
MyObject<MyParaClass>
的对象,并尝试将其传递给Print
方法时,构建失败,因为它无法将MyObject<MyParaClass>
转换为MyObject<IMyParaInterface>
I thought there should be not an issue as MyParaClass
implements IMyParaInterface
.How to solve this or get around? 我认为
MyParaClass
实现IMyParaInterface
应该没有问题, MyParaClass
解决或解决这个问题?
You should define your Print method as a template method: 您应该将Print方法定义为模板方法:
void Print<T>(MyObject<T> parameter) where T : IMyParaInterface {}
Which means, that the method would take any MyObject<> instance, whose type argument implements your IMyParaInterface interface. 这意味着该方法将采用任何MyObject <>实例,该实例的type参数实现您的IMyParaInterface接口。
The problem with your original Print() code is, that it only accepts MyObject< IMyParaInterface > as input. 原始Print()代码的问题在于,它仅接受MyObject <IMyParaInterface>作为输入。 Note, that MyObject< MyParaClass > is not instance of type MyObject< IMyParaInterface >.
请注意,MyObject <MyParaClass>不是MyObject <IMyParaInterface>类型的实例。
There is another solution , where you can use .net's Covariance / contravariance features, by defining an interface for your object, where the type parameter will be marked as covariant ( out T). 还有另一种解决方案 ,您可以通过定义对象的接口来使用.net的协方差/逆方差功能,其中类型参数将被标记为协变( out T)。
public interface IMyObject<out T> where T: IMyParaInterface {}
public class MyObject<T> : IMyObject<T> where T: IMyParaInterface {}
public static void Print(IMyObject<IMyParaInterface> parameter) {}
In this case, MyObject< MyParaClass > will be type-compatible with IMyObject< IMyParaInterface >. 在这种情况下,MyObject <MyParaClass>将与IMyObject <IMyParaInterface>类型兼容。
You can read about covariance / contravariance here: https://docs.microsoft.com/en-us/dotnet/standard/generics/covariance-and-contravariance 您可以在此处阅读有关协方差/逆方差的信息: https : //docs.microsoft.com/zh-cn/dotnet/standard/generics/covariance-and-contravariance
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.