我正在尝试创建特定类的类型,但我无法将它们作为通用表示返回,有人可以告诉我如何实现吗?我对逆/协方差魔法有点了解
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
{
}
最佳答案
让我们重命名您的类型。
interface IAnimal {}
class Cage<T> where T : IAnimal {}
class Tiger : IAnimal {}
你的问题是:我有一个 Cage<Tiger>
我希望它被用作 Cage<IAnimal>
因为老虎是一种动物。
现在你明白为什么这是非法的了吗?老虎笼只能关老虎;动物笼子可以容纳任何动物。如果老虎的笼子可以用作动物的笼子,那么你可以在老虎笼子里放一条鱼,老虎和鱼都不会高兴。
您想要的是泛型类协变,但 C# 仅支持接口(interface)和委托(delegate)上的泛型协变。
关于c# - 泛型的反/协方差问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32448965/