Home >Backend Development >C++ >Can List Be Assigned to List in C#?
C# type variance problem: Sign the list & lt; assignment type & gt; assign a value to list & lt; base type & gt;
In the problem of list & lt; derived type & gt; assigned to list & lt; base type & gt; Is there any solution?
Example
Consider the following code:
Cooperation
<code class="language-csharp">class Animal { } class Giraffe : Animal { } static void Main(string[] args) { // 数组赋值成功 Animal[] animals = new Giraffe[10]; // 隐式赋值失败 List<Animal> animalsList = new List<Giraffe>(); // 错误 // 显式转换失败 List<Animal> animalsList2 = (List<Animal>)new List<Giraffe>(); // 错误 }</code>
Coordination is the ability to hold the derived type object when declared that the data structure can hold a base type object. In the above example, List can hold an object of the Animal or any derived type (such as Giraffe).
The square difference in the array and list
will fail. Unsafe square difference
The safety difference in the c# 4
C# 4 introduced support for the security generic variance in the interface and entrustment. The interfaces such as Func (collaborative) and entrustment like ACTION(inverse) ensure type security.
<code class="language-csharp">List<Giraffe> giraffes = new List<Giraffe>(); giraffes.Add(new Giraffe()); List<Animal> animals = giraffes; // 错误 animals.Add(new Lion()); // 不安全,违反类型安全</code>Solution
In C# 2, if you do not need to maintain a single list, you can use list
.convertall to create a new list with the need type.
The above is the detailed content of Can List Be Assigned to List in C#?. For more information, please follow other related articles on the PHP Chinese website!