如何通过可用的约束类型方法将泛型 class 作为参数传递

How Pass Generics class as parameter with constraint type methods available

我仍在尝试完全理解泛型,尤其是与基础 classes 结合使用时。我有一个通用 table class 接受行的派生类型 class 但被限制为基行。由于基础 table class 是采用类型基础行的约束,我如何将此 class 与任何派生的 class 传递为基础行类型。

public interface Itable<in TRow>  where TRow : row{
    //*This will not compile with the list of TRow should it be List<row>? If so how do i force that conversion?
    List<TRow> IfindLst();
}
public abstract class table<TRow> where TRow : row, Itable<row>
{
    //*This is the list of rows i want to be able to send as their base row 
    public List<TRow> derivedRowLst = new List<TRow>();
    public table()
    {

    }
    public List<row> IfindLst()
   {
       return derivedRowLst;
   }
}
//Derive instance of base table class
public class tableInstOne : table<rowInstOne>
{

}
//Base class for row that all derived rows are guarantee to be of
public abstract class row
{

}
public class rowInstOne : row
{
    public rowInstOne() { }
}
public class tester
{
    public static void main()
    {
        Itable<row> tblInstOne = new tableInstOne();
        //*This is what I am trying to figure out how to do get this list of base row class from the base table class. Even though it is stored as List<TRow> or derived row class. 
        List<row> baseLst = tblInstOne.IfindLst();
    }

}

这不允许我将实例化的 table class 作为其基本保证类型发送。我以前没有 table class 作为通用,所以所有行都只用作基行,但这需要在我试图避免的代码中的其他点进行向下转换。现在我不必向下转换但是我不能将这个 table class 以 base 作为参数发送到 classes 不关心派生行类型并且只需要利用基行函数。感谢您的帮助!

很难准确地说出你想要完成什么。也许下面的代码会有所帮助。请注意,方法 IfindLst returns 是 List<TRow> 而不是 List<Row>,我认为这可能是您问题的一部分。

public abstract class Table<TRow> where TRow : Row
{
    //*This is the list of rows i want to be able to send as their base row 
    public List<TRow> derivedRowLst = new List<TRow>();
    public Table()
    {

    }
    public List<TRow> IfindLst()
    {
       return derivedRowLst;
    }
}
//Derive instance of base table class
public class TableInstOne : Table<RowInstOne>
{

}
//Base class for row that all derived rows are guarantee to be of
public abstract class Row
{

}
public class RowInstOne : Row
{
    public RowInstOne() { }
}

public static class Program
{
    public static void Main(string[] args)
    {
        Table<RowInstOne> tblInstOne = new TableInstOne();
        //*This is what I am trying to figure out how to do get this list of base row class from the base table class. Even though it is stored as List<TRow> or derived row class. 
        List<Row> baseLst = tblInstOne.IfindLst().OfType<Row>().ToList();
        List<Row> baseLst2 = tblInstOne.IfindLst().ConvertAll(x => (Row)x);
        List<Row> baseLst3 = tblInstOne.IfindLst().Cast<Row>().ToList();
        IEnumerable<Row> baseLst3 = tblInstOne.IfindLst();
    }
}

注意最后一行我演示了协变 IEnumerable<T> 接口的使用,以避免任何类型转换或运行时类型检查。