The inheritance mechanism allows us to create new classes based on the existing class, but the same concept is not directly applicable to generic lists. Specifically, we cannot declare a
and assign a list of derived types, even if the derived class inherits the self -based class. Please consider the following example:
List<基类>
interface A { } class B : A { } class C : B { } class Test { static void Main(string[] args) { A a = new C(); // 正确 List<A> listOfA = new List<C>(); // 编译错误 } }
<换> conversion method
The method of converting <换> to is to iterate the list elements and manually convert them manually. This can be implemented using
Method:
List<派生类>
List<基类>
Here, each of the elements in the iteratory C list convert it to type A and add it to the new Listofa list. ConvertAll
List<A> listOfA = new List<C>().ConvertAll(x => (A)x);
or, we can use Linq to execute the conversion:
Here, convert each element in the list to type A, and
creates a new list containing the conversion element.The above is the detailed content of How to Convert a List of Derived Classes to a List of Base Classes in C#?. For more information, please follow other related articles on the PHP Chinese website!