我有一个属性,如下所示:
public ITypeA<IType2> MyProperty {
get {
return new ImplementationA<ImplementationB>();
}
}
我怎样才能做到这一点。 (new ImplementationA<ImplementationB>() as ITypeA<IType2>)
返回null,不允许强制转换。
答案 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>()
};
}
}