C# generic difference: assign a list & lt; assignment class & gt; assign a value to list & lt; base class & gt;
When using a generic list in C#, try to assign the list of derived type to the list of the type of derived type. This problem is caused by conflict between the type of safety and compilation of type safety during runtime.
Question and code example
Consider the following code:
In this example, due to the runtime check, it is effective to assign the giraffe array to the animal array. However, the distribution of List to List
will cause errors during compilation.<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>
Different and security issues
assigning a value to List will be considered a coordinated change.
However, this assignment can cause security issues. If the new lion object is added to AnimalSList, it can be assigned to AnimalSList2 without any compilation check, even if it violates the type of animal list type safety.
Use the array for running during runtime:
The array supports the reference type variance during runtime, which allows assigning the derived type array to the base type array.
C# 4 The security square difference:
C# 4 introduces the support for the security variance of interfaces and entrustment. Func
C# 2 Method: In C# 2, you can use List
.Convertall to create a new list with the required type.
Conclusion
The above is the detailed content of Why Can't I Assign List to List in C#?. For more information, please follow other related articles on the PHP Chinese website!