将基类型列表转换为继承类型列表

ste*_*yer 19 c# generic-list

我确信这个问题可以解决上一个问题中提出的问题,但我无法找到它.

C#类中有一个方法,它将基类的通用List作为参数.我需要传递一个继承类的列表,并且不知道如何执行此操作.我的尝试中出错了.以下是示例代码:

public class A
{
   public static void MethodC(List<A>)
   {
       // Do Something here with the list
    }
}
public Class B : A
{
   // B inherits from A, A is the Base Class   
}

// Code utilizing the above method 
List<B> listOfB = new List<B>();
A.MethodC( (List<A>) listOfB );  // Error: this does not work
A.MethodC( listOfB.ToList<typeof(A)>() ); // Error: this does not work
A.MethodC( listOfB.ConvertAll<A>(typeof(A)) ); // Error: this does not work
// how can I accomplish this?  It should be possible I would think
Run Code Online (Sandbox Code Playgroud)

注意:这是我的最终工作方法作为参考.我对我的问题有了更好的解决方案,但从技术上讲,这不是问题的答案,因为我的问题是不正确的.

 public static DataTable 
    ObjectCollectionToDataTable<GLIST>
      (List<GLIST> ObjectCollection) where GLIST 
              : BaseBusinessObject
        {
            DataTable ret = null;

            if (ObjectCollection != null)
            {
                foreach ( var b in ObjectCollection)
                {

                    DataTable dt = b.ToDataTable();
                    if (ret == null)
                        ret = dt.Clone();
                    if (dt.Rows.Count > 0)
                        ret.Rows.Add(dt.Rows[0].ItemArray);
                }
            }

            return ret;
        }
Run Code Online (Sandbox Code Playgroud)

Qui*_*son 30

如果你有linq,你可以做到

var ListOfA = ListOfB.Cast<A>().ToList();
Run Code Online (Sandbox Code Playgroud)


Dan*_*ker 9

你不能这样做.要理解为什么它不被允许,想象一下如果在它被强制转换为a Add后被调用会发生什么.List<Derived>List<Base>

此外,暗示C#4.0将不同的答案是错误的.永远不会修改列表以允许您执行此操作.只会IEnumerable- 因为它不允许将项目添加到集合中.

更新:它在你所使用的解决方案中工作的原因是因为你不再传递相同的列表.您正在创建一个全新的列表,它是原始列表的副本.这就是我询问修改清单的原因; 如果MethodC更改列表中的项目数,则会对副本进行更改,而不是原始列表.

我认为理想的解决方案如下:

public abstract class A
{
    public void MethodC<TItem>(List<TItem> list) where TItem : A
    {
        foreach (var item in list)
            item.CanBeCalled();
    }

    public abstract void CanBeCalled();
}

public class B : A
{
    public override void CanBeCalled()
    {
        Console.WriteLine("Calling into B");
    }
}

class Program
{
    static void Main(string[] args)
    {
        List<B> listOfB = new List<B>();

        A a = new B();

        a.MethodC(listOfB);
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,使用此解决方案,您可以List<B>直接传递给它,MethodC而无需首先对它进行奇怪的转换.所以没有必要的复制.

这样做的原因是因为我们已经告诉MethodC接受一个源自的任何事物的列表A,而不是坚持它必须是一个列表A.