如何将泛型类用作具有约束类型方法的参数

问题描述 投票:0回答:1

我仍在尝试完全理解泛型,尤其是与基类一起使用时。我有一个通用的表类,它接受行类的派生类型,但被约束为基行。由于基表类对采用基本行类型具有约束,因此我如何将此类与任何派生类一起传递为基行类型。

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();
    }

}

这不允许我将实例化表类作为具有基本保证类型的类发送。我以前没有将表类作为通用类,因此所有行都仅用作基本行,但这需要在我试图避免的代码的其他点进行向下转换。现在,我不必向下转换,但我无法将此表类以base作为参数发送给不关心派生行类型而只需要利用基本行函数的类。感谢您的帮助!

c# generics contravariance
1个回答
0
投票

很难准确说明您要完成的目标。也许以下代码会有所帮助。请注意,方法IfindLst返回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>接口的使用,以避免任何强制转换或运行时类型检查。

© www.soinside.com 2019 - 2024. All rights reserved.