c# – 无法将通用类的子类添加到列表中
发布时间:2020-12-16 01:27:45 所属栏目:百科 来源:网络整理
导读:我有一个抽象的Content类和具体的子类 public abstract class Contentpublic class ContentA : Contentpublic class ContentB : Content 我还有一个抽象的通用ContentSource类和具体的子类 public abstract class ContentSourceT where T : Contentpublic cl
我有一个抽象的Content类和具体的子类
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(),}; Working example 您仍然可以使用抽象类,但列表仍然必须是接口列表: 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? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |