Convert derived class list to base class list
Covariance means that a derived type can replace its base type without losing any functionality. In this case, we have a base class (Animal) and a derived class (Cat), where the base class contains a virtual method Play that accepts a List as input parameter.
The following code demonstrates the conversion problem:
<code class="language-csharp">using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication9 { class Animal { public virtual void Play(List<Animal> animals) { } } class Cat : Animal { public override void Play(List<Animal> animals) { } } class Program { static void Main(string[] args) { Cat cat = new Cat(); cat.Play(new List<Cat>()); } } }</code>
Compiling the code will result in the error: Argument 1: cannot convert from 'System.Collections.Generic.List
This error occurs because List is a writable data structure. If we allow conversion from List
To solve this problem, C# 4 introduced a concept called "generic covariance" for known-safe interfaces. IEnumerable
We can solve the conversion problem by modifying the Play method to accept an IEnumerable
<code class="language-csharp">class Animal { public virtual void Play(IEnumerable<Animal> animals) { } } class Cat : Animal { public override void Play(IEnumerable<Animal> animals) { } } class Program { static void Main() { Cat cat = new Cat(); cat.Play(new List<Cat>()); } }</code>
By using the IEnumerable<T>
interface instead of List<T>
, we take advantage of the covariance feature of C#, avoid type conversion errors, and ensure the safety of the code. IEnumerable<T>
only allows data to be read, not modified, so it is safe to convert List<Cat>
to IEnumerable<Animal>
.
The above is the detailed content of Can I Cast a `List` to a `List` in C#?. For more information, please follow other related articles on the PHP Chinese website!