How to cast a list
I have a class A and a class B, class B is inherit from cla开发者_StackOverflow中文版ss A. Assume that I have:
A a1 = new B();
A a2 = new B();
List<A> LA = new List<A>{a1, a2};
Please help me how to convert List to List. I try to use List<B> LB = (List<B>)LA
but get compiling error "Can't convert List<A> to List<B>"
.
Please help me. Thanks.
Note: only .NET 2.0. Thanks.
You have to cast each item in the list, not the whole list.
List<A> listA = new List<A>();
List<B> listB = new List<B>();
for (int i = 0; i < listA.Count; i++)
{
listB.Add((B)listA[i]);
}
If you are in .NET 2.0, then I beleive that you are stuck enumerating over the list and casting each element independently. With .NET 3.5, you could use a "Select" extension method to cast them all with a single line of code.
You can do it this way:
List<A> la = new List<A>();
List<B> lb = new List<B>();
foreach( A a in la )
{
if (a is B)
lb.Add((B)a);
else
{
// ignore or throw an exeption
}
}
Can you try something on these lines
LA.ForEach(delegate(A emp) { emp = (B)emp; });
精彩评论