Home > Backend Development > C++ > How to Convert a List of Derived Classes to a List of Base Classes in C#?

How to Convert a List of Derived Classes to a List of Base Classes in C#?

Mary-Kate Olsen
Release: 2025-02-01 17:41:10
Original
999 people have browsed it

How to Convert a List of Derived Classes to a List of Base Classes in C#?

C#Lyrics are transformed into a list of base class

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<基类>

This code fails during compilation, because the compiler expects a list of an A object, not the list of the C object. To solve this problem, we need to convert the list of derived objects into a list of base objects.
<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>
Copy after login

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

The alternative method of using linq
<code class="language-csharp">List<A> listOfA = new List<C>().ConvertAll(x => (A)x);</code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template