Can you subclass a generics class with a specific typed class?

梦想的初衷 提交于 2019-12-04 02:54:37

In C#, covariance (assigning a derived type to a base type) cannot be applied to generic classes. As a result, you would need to apply an interface specifically marked as covariant, using the out parameter modifier on a new IGenericBase interface.

protected IGenericBase<Interface1> genericInstance = new Customer();

public interface IGenericBase<out T> {}

public abstract class GenericBase<T> : IGenericBase<T>
    where T:Interface1 {}

public interface Interface1 {}

public class Type1 : Interface1 {}

public class Customer: GenericBase<Type1> {}

C# doesn't have covariance of generic classes, which basically means you cannot assign a value with a more derived type argument to a variable with a less derived type argument.

That would work with interfaces, though, provided some conditions are satisfied, namely, if the parameter-type is used in covariant positions only, i.e. as a return type of methods and properties.

Refer to this and other bits of documentation for more info.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!