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
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>(); // 错误 }
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.
List<Giraffe> giraffes = new List<Giraffe>(); giraffes.Add(new Giraffe()); List<Animal> animals = giraffes; // 错误 animals.Add(new Lion()); // 不安全,违反类型安全
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!