我有一个带有类约束的泛型类。
public class MyContainer<T> where T : MyBaseRow
MyBaseRow 是一个抽象类,我还想包含一个 MyContainer 的成员。
public abstract class MyBaseRow
{
public MyContainer<MyBaseRow> ParentContainer;
public MyBaseRow(MyContainer<MyBaseRow> parentContainer)
{
ParentContainer = parentContainer;
}
}
我在使用从 MyBaseRow 继承的类的构造函数时遇到问题,例如。
public class MyInheritedRowA : MyBaseRow
{
public MyInheritedRowA(MyContainer<MyInheritedRowA> parentContainer)
: base(parentContainer)
{ }
}
不允许在构造函数中使用 MyInheritedRowA,编译器只期望也只允许使用 MyBaseRow。我认为通用类约束允许继承?我在这里做错了什么,有什么办法可以重新设计这些类来解决这个问题吗? 非常感谢您的任何回复。
最佳答案
基本上,您不能以这种方式使用泛型,因为协方差系统不能以这种方式与类一起工作。看这里:http://geekswithblogs.net/abhijeetp/archive/2010/01/10/covariance-and-contravariance-in-c-4.0.aspx
不过您可以使用这样的界面:
public interface MyContainer<out T> where T : MyBaseRow {
}
并且该代码将编译。
关于c# - 通用构造函数和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11873524/