You aren't able to make the assignment because the base class, AbstractClass<T>
, is invariant. What you want to be able to make that kind of assignment is a covariant type. Defining Covariance and Contravariance is limited to interfaces, so that means we need another interface.
public interface IAbstractClass<out T> where T : BaseInterface { }
public abstract class AbstractClass<T> : IAbstractClass<T> where T : BaseInterface { }
The out
keyword marks the generic type parameter as covariant. We then implement that interface in AbstractClass<T>
, and our other types can work expected through the interface. These are also the only alterations we need to make, we leave the other type definitions the same:
public interface BaseInterface { }
public interface ChildInterface : BaseInterface { }
public class ConcreteClass : AbstractClass<ChildInterface> { }
We now have a covariant interface that AbstractClass<T>
implements, and you can do the kind of assignment you desire, but you'll have to target the IAbstractClass
interface.
public void Main() {
IAbstractClass<BaseInterface> c = new ConcreteClass();
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…