无法将通用类的子类添加到列表中

sea*_*000 3 c# generics

我有一个抽象Content类和具体的子类

public abstract class Content

public class ContentA : Content

public class ContentB : Content
Run Code Online (Sandbox Code Playgroud)

我还有一个抽象的泛型ContentSource类和具体的子类

public abstract class ContentSource<T> where T : Content

public class SourceX : ContentSource<ContentA>

public class SourceY : ContentSource<ContentB>
Run Code Online (Sandbox Code Playgroud)

我希望有一个ContentSource<Content>对象列表作为子类ContentSource

var ContentSources = new List<ContentSource<Content>>
{
    new SourceX(),
    new SourceY(),
};
Run Code Online (Sandbox Code Playgroud)

但这不编译 - 我得到一个'无法从SourceX转换为ContentSource'错误.

为什么这不起作用?

Kob*_*obi 5

这可以使用协方差在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(),
};
Run Code Online (Sandbox Code Playgroud)

工作示例
这很好地解释这里:<out T>VS <T>中的泛型

您仍然可以使用抽象类,但列表仍然必须是接口列表:

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> {}
Run Code Online (Sandbox Code Playgroud)

还有一个很好的解释为什么不支持类:为什么C#(4.0)不允许泛型类的共同和逆变?