与泛型的对立/协方差问题

Rus*_*kin 3 .net c# generics

我尝试创建特定类的类型,但我不能将它们作为通用表示返回,有人可以告诉我如何实现它吗?对于反对/协方差魔法,我有点轻松

public DashboardNotification<IDashboardEntry> Get()
{
    //return new MyNotWorkingNotification(); // doesn't compile, I want to achieve this
    return new MyWorkingNotification(); // compiles
}

public class DashboardNotification<T> where T : IDashboardEntry
{
}

public interface IDashboardEntry
{
}

public class MyNotWorkingNotification : DashboardNotification<MyDashboardEntry>
{
}

public class MyWorkingNotification : DashboardNotification<IDashboardEntry>
{
}

public class MyDashboardEntry : IDashboardEntry
{
}
Run Code Online (Sandbox Code Playgroud)

Eri*_*ert 6

让我们重命名你的类型.

interface IAnimal {}
class Cage<T> where T : IAnimal {}
class Tiger : IAnimal {}
Run Code Online (Sandbox Code Playgroud)

你的问题是:我有一个Cage<Tiger>,我希望它被用作一个Cage<IAnimal>因为老虎是一种动物.

现在你明白为什么这是非法的吗?老虎笼只能容纳老虎; 一笼动物可以容纳任何动物.如果一只老虎笼可以用作动物的笼子,那么你可以将鱼放入虎笼中,这样既不会让老虎也不会让鱼感到高兴.

您想要的是泛型类协方差,但C#仅支持接口和委托的通用协方差.