为什么我不能在函数中引用子类的列表,而需要父类的列表?

  • 本文关键字:列表 父类 子类 引用 不能 函数 c#
  • 更新时间 :
  • 英文 :

public class A {
    public int ID {get;set;}
    public List<int> Things {get;set}
}
public class B : A {
    public string Name {get;set;}
}
public static FillListAThings(ref List<A> lstA){
 // ...
 // code to fill the Things list in each A of lstA with bulk call to database containing all A's IDs from lstA
 // ...
}
public static GetBList(){
  var lstB = new List<B>();
  // ...
  // Fill B list, get IDs and names
  // ...
  // ERROR here, since ref List<B> cannot be converted to a ref List<A>
  FillListAThings(ref lstB); 
}

我可以理解无法将 ref 列表 A 传递给期望 ref 列表 B 的函数,因为类中会缺少成员,但为什么这是不可能的?我也不能通过 LINQ 将其转换为列表 A,因为那样它就会变成无法引用的一次性变量。

我目前的解决方法是强制转换为列表 A 的临时变量,将其发送到要填充的函数,然后通过在其 ID 上交叉将属性复制回原始列表。

// workaround
var tmpListA = lstB.Cast<A>().ToList();
FillListAThings(ref tmpListA);
foreach(var b in lstB)
{
    var a = tmpListA.Where(x => x.ID == b.ID);
    // ... 
    // code to copy properties
    // ...
}

你可以,但你需要扩大你的方法签名,以接受所有实现AList<T>类型,而不仅仅是List<A>本身。

public static void FillListAThings<T>(ref List<T> lstA) where T : A
{
    // ...
    // code to fill the Things list in each A of lstA with bulk call to database containing all A's IDs from lstA
    // ...
}

最新更新