我有一个抽象的Content类和具体的子类 public abstract class Contentpublic class ContentA : Contentpublic class ContentB : Content 我还有一个抽象的通用ContentSource类和具体的子类 public abstract class ContentSour
public abstract class Content public class ContentA : Content public class ContentB : Content
我还有一个抽象的通用ContentSource类和具体的子类
public abstract class ContentSource<T> where T : Content public class SourceX : ContentSource<ContentA> public class SourceY : ContentSource<ContentB>
我想要一份ContentSource< Content>列表作为ContentSource子类的对象
var ContentSources = new List<ContentSource<Content>>
{
new SourceX(),
new SourceY(),
};
但这不编译 – 我得到一个’无法从SourceX转换为ContentSource’错误.
为什么这不起作用?
这可以使用 covariance在C#中实现,但您必须使用接口作为列表类型:public interface IContentSource<out T> where T : Content {}
public class SourceX : IContentSource<ContentA> {}
public class SourceY : IContentSource<ContentB> {}
var ContentSources = new List<IContentSource<Content>>
{
new SourceX(),
new SourceY(),
};
Working example
这里很好地解释了这个:<out T> vs <T> in Generics
您仍然可以使用抽象类,但列表仍然必须是接口列表:
public interface IContentSource<out T> where T : Content {}
public abstract class ContentSource<T> : IContentSource<T> where T : Content {}
public class SourceX : ContentSource<ContentA> {}
public class SourceY : ContentSource<ContentB> {}
还有一个很好的解释为什么它不支持类:Why does C# (4.0) not allow co- and contravariance in generic class types?
