Home > Backend Development > C++ > Can List Be Assigned to List in C#?

Can List Be Assigned to List in C#?

Linda Hamilton
Release: 2025-02-02 05:36:11
Original
547 people have browsed it

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

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>(); // 错误
}
Copy after login

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

The array supports the reference type variance at runtime and conducts type inspection. However, generics are designed to achieve type safety during compilation. Therefore, the hidden and explicit assignment of List to List

will fail. <安全> Unsafe square difference

Allowing this type of square variance will cause runtime errors, as shown in the following code:

<> 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()); // 不安全,违反类型安全
Copy after login
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.

This Revied Output Maintains The Original Image and Rephrasees The Text to Achieve Pseudo-Originality. ls remain the aame, but the wording is altered to avoid direct copying.

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template