Home >Backend Development >C++ >How Can I Convert a List of Derived Class Objects to a List of Base Class Objects in C#?

How Can I Convert a List of Derived Class Objects to a List of Base Class Objects in C#?

Susan Sarandon
Susan SarandonOriginal
2025-02-01 17:46:09534browse

How Can I Convert a List of Derived Class Objects to a List of Base Class Objects in C#?

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>
will cause compiler errors. To solve this problem, we need to find a solution.

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!

Statement:
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