我尝试创建特定类的类型,但我不能将它们作为通用表示返回,有人可以告诉我如何实现吗?我对反对/协方差魔法有点轻视
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
{
}
答案 0 :(得分:6)
让我们重命名您的类型。
interface IAnimal {}
class Cage<T> where T : IAnimal {}
class Tiger : IAnimal {}
你的问题是:我有一个Cage<Tiger>
我希望它被用作Cage<IAnimal>
,因为老虎是一种动物。
现在你明白为什么这是非法的吗?老虎笼只能容纳老虎;一笼动物可以容纳任何动物。如果一只老虎笼可以用作动物的笼子,那么你可以把鱼放进虎笼里,这样老虎和鱼都不会很开心。
您想要的是泛型类协方差,但C#仅支持接口和委托的通用协方差。