Home >Backend Development >C++ >Why Can't I Cast a `List` to a `List` in C#?
cannot be converted to List<string>
? List<object>
objects to List<string>
variables to cause an interesting abnormality. Why this conversion is not allowed and has always troubled many developers. List<object>
Consider the following code fragment:
Interest and explicit conversion attempts failed, which made us wonder the reason.
<code class="language-csharp">List<string> sl = new List<string>(); List<object> ol; ol = sl; // 隐式转换不被允许 ol = (List<object>)sl; // 显式转换也失败</code>
The root cause
The main reason for this limit is that inconsistency may occur within the list. If we allow this conversion and then add the type of to the list to the list, the string list will become inconsistent.
When the first list of the iteration is referenced, we will encounter an abnormal class conversion, because the Foo
instance cannot be converted to a string. Maintenance type consistency is essential to ensure the integrity of data in the list.
Reverse conversion: more in -depth discussion Foo
However, about reverse conversion, an interesting problem appeared:
Is this conversion allowed? Although it may seem useful, allowing this conversion may be error or inconsistency during runtime. From a more general class () to the conversion of more specific classes (), any object added to the string list may not be compatible with the object list.
<code class="language-csharp">List<object> ol = new List<object>(); List<string> sl; sl = (List<string>)ol;</code>Can the reverse conversion be successful in C#?
object
It is not clear whether this reverse conversion is legal in C#. If it is legal, it will highlight the difference between the display hidden conversion and the explicit conversion, and the latter seems to violate the type consistency rule. Further testing and clarification of this aspect will be very valuable. string
The above is the detailed content of Why Can't I Cast a `List` to a `List` in C#?. For more information, please follow other related articles on the PHP Chinese website!