
Safely convert List
In C#, when dealing with inheritance and generic types, you may encounter situations where you need to convert a list of derived class objects into a list of base class objects. This can cause problems if the base class contains virtual methods that are overridden in the derived class.
Consider the following example:
<code class="language-csharp">class Animal
{
public virtual void Play(List<Animal> animals) { }
}
class Cat : Animal
{
public override void Play(List<Animal> animals)
{
// Cat 特定的实现
}
}
class Program
{
static void Main(string[] args)
{
Cat cat = new Cat();
cat.Play(new List<Cat>()); // 错误:参数 1 无法从“System.Collections.Generic.List<Cat>”转换为“System.Collections.Generic.List<Animal>”
}
}</code>When compiling this code, you will encounter the error message "Parameter 1: Cannot convert from 'System.Collections.Generic.List
In order to solve this problem, you need to understand the concept of generic covariance. Generic covariance allows you to safely extend the type of a parameter in a derived class override. In this case, you want to extend the parameter type from List
C# 4 introduces support for generic covariance, with the help of IEnumerable
<code class="language-csharp">public virtual void Play(IEnumerable<Animal> animals) { }</code>Then override it in Cat class:
<code class="language-csharp">public override void Play(IEnumerable<Animal> animals) { }</code>You can make the Play method covariantly safe. This allows you to pass a List
<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>This code will compile and execute successfully without errors, allowing you to safely convert List< when a base class method is defined using IEnumerable
The above is the detailed content of How Can I Safely Cast a `List` to a `List` in C#?. For more information, please follow other related articles on the PHP Chinese website!
Why can't the video in ppt play?
How to use insert statement in mysql
What is the roaming folder for?
How to read a column in excel in python
Is java front-end or back-end?
How to use div tags
Can data between Hongmeng system and Android system be interoperable?
The most prominent features of computer networks