将继承类型转换为泛型

时间:2012-02-02 19:35:46

标签: c# generics

我有一个属性,如下所示:

public ITypeA<IType2> MyProperty {
   get {
      return new ImplementationA<ImplementationB>();
   }
}

我怎样才能做到这一点。 (new ImplementationA<ImplementationB>() as ITypeA<IType2>)返回null,不允许强制转换。

2 个答案:

答案 0 :(得分:2)

您需要使用covariant将接口的泛型参数声明为out keyword

答案 1 :(得分:0)

对于.NET 3.5,我认为您最好的选择是使用wrappr:

class ImplementationWrapper : ITypeA<IType2>
{
    public ImplementationA<ImplementationB> MyObject { get; set; }
}

public ITypeA<IType2> MyProperty {
    get {
        return new ImplementationWrapper {
            MyObject = new ImplementationA<ImplementationB>()
        };
   }
}