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

Can List Be Assigned to List in C#?

Linda Hamilton
Linda HamiltonOriginal
2025-02-02 05:36:11491browse

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

<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>

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.

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