The converting from the derivative class to the base class list
In object -oriented programming, inheritance class classes and interfaces are very common practices. However, when dealing with a collection, we encounter an obvious limit: Why can't we use the same class or interface as the base class to define the list?
Consider the following example:
Try to instance into
<code class="language-csharp">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>(); // 编译器错误 } }</code>
listOfA
Solution: Expressive conversion and linq List<C>
One method is to manually traverses the list and convert each element into the required base type. This can be implemented using Method:
Another solution using linq is to use the ConvertAll
operator to convert the entire list:
<code class="language-csharp">List<A> listOfA = new List<C>().ConvertAll(x => (A)x);</code>
By using these technologies, we can effectively convert the list of derived classes into a list of its base type, so that we have greater flexibility when dealing with inheritance schemes. Cast
The above is the detailed content of How Can I Convert a List of Derived Class Objects to a List of Base Class Objects in C#?. For more information, please follow other related articles on the PHP Chinese website!