Home > Backend Development > C++ > Why Can't a `List` Be Assigned to a `List` Variable in C#?

Why Can't a `List` Be Assigned to a `List` Variable in C#?

Barbara Streisand
Release: 2025-01-28 13:46:09
Original
394 people have browsed it

Why Can't a `List` Be Assigned to a `List` Variable in C#?

Why can't the

object value variable? List<string> List<object> In C#, try to assign objects to

variables can cause errors during compilation. This operation is not allowed even if it is explicitly converted. Let's explore the principle behind it:

List<string> Consider the following scene: List<object>

If this conversion can be successfully executed, what will happen if you add a type of

to the
<code class="language-csharp">List<string> sl = new List<string>();
List<object> ol;
ol = sl; // 产生编译时错误</code>
Copy after login
list? This will create an inconsistency in the

list, because the ol list expects only the string. When traversing the list, encountering the Foo instance will cause the class conversion abnormality, indicating that it cannot be converted into a string. sl sl On the contrary, the conversion from to sl may be useful. By converting from a more general class () to a more specific class (Foo), it ensures that adding any elements to the string list will not violate the constraints of the object list. However, C# may not support this type of conversion.

The above is the detailed content of Why Can't a `List` Be Assigned to a `List` Variable in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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