For example, consider the following code:
In this code, the list of the Giraffe object is assigned to the list referenced by Animal. However, this assignment failed during compilation due to the problem of coordination.
class Animal { } class Giraffe : Animal { } static void Main(string[] args) { List<Giraffe> giraffes = new List<Giraffe>(); List<Animal> animals = giraffes; // 编译时错误 }
<变> Cooperation and non -variability
C #'s generic types can be coordinated or unchanged. Coordination allows base class references to reference the derived class objects, while non -degeneration prevents such assignments. For the list, the default behavior is non -variability, which means that list cannot be assigned to list
.
In order to solve this problem, there are several solutions:
<式> Explicit conversion:The following code can be used to display list
to listList<Animal> animals = (List<Animal>)giraffes; // 不推荐,可能导致运行时错误
.Convertall method to convert List
to ListList<Animal> animals = giraffes.ConvertAll(g => (Animal)g);
Which method to choose depends on the specific situation and the requirements for the robustness of the code. ICovariant<out T>
The above is the detailed content of Can I Assign a List of Derived Class Objects to a Base Class List in C#?. For more information, please follow other related articles on the PHP Chinese website!