Design pattern: polymorphisim for list of objects

Posted by ziang on Stack Overflow See other posts from Stack Overflow or by ziang
Published on 2010-04-28T03:46:40Z Indexed on 2010/04/28 3:53 UTC
Read the original article Hit count: 233

Filed under:
|
|

Suppose I have a class A, and A1, A2 inherits from A. There are 2 functions:

List<A1> getListA1(){...}
List<A2> getListA2(){...}

Now I want to do something similar to both A1 and A2 in another function

public void process(List<A>){...}

If I want to pass the instance of either ListA1 or ListA2, of course the types doesn't match because the compiler doesn't allow the coercion from List< A1> to List< A>. I can't do something like this:

List<A1> listA1 = getListA1();
List<A> newList = (List<A>)listA1; //this is not allowed.

So what is the best approach to the process()? Is there any way to do it in a universal way rather than write the similar code to both List and List?

© Stack Overflow or respective owner

Related posts about c#

Related posts about java