Why can't the
object value variable? List<string>
List<object>
In C#, try to assign objects to
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>
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!