Home >Backend Development >C++ >Can I Assign a List of Derived Class Objects to a Base Class List in C#?
C# In the C# programming language, a list of derived class objects to the base class reference list will trigger the problem of collaboration. This problem occurs when the derived category does not exist in the base class.
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.
<code class="language-csharp">class Animal { } class Giraffe : Animal { } static void Main(string[] args) { List<Giraffe> giraffes = new List<Giraffe>(); List<Animal> animals = giraffes; // 编译时错误 }</code>
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 list<code class="language-csharp">List<Animal> animals = (List<Animal>)giraffes; // 不推荐,可能导致运行时错误</code>You can use the list
.Convertall method to convert List
to List<code class="language-csharp">List<Animal> animals = giraffes.ConvertAll(g => (Animal)g);</code>It can be explicitly specified to specify the collaborative change of generic types through custom interfaces. By implementing the icovariant
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!