C#   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了c# – 无法将通用类的子类添加到列表中大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个抽象的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
这里很好地解释了这个:<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?

大佬总结

以上是大佬教程为你收集整理的c# – 无法将通用类的子类添加到列表中全部内容,希望文章能够帮你解决c# – 无法将通用类的子类添加到列表中所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。