【发布时间】:2021-05-07 06:30:04
【问题描述】:
代码:
object obj = new List<object>() { "a", "b" };
List<string> list = (List<string>)obj;
例外:
System.InvalidCastException
HResult=0x80004002
Message=Unable to cast object of type 'System.Collections.Generic.List`1[System.Object]' to type 'System.Collections.Generic.List`1[System.String]'.
Source=ConsoleApp2
StackTrace:
at ConsoleApp2.Program.Main(String[] args) in
C:\Users\guoswang\source\repos\ConsoleApp2\ConsoleApp2\Program.cs:line 12
我知道如何避免这种情况,但想了解根本原因。
【问题讨论】:
-
那些对象真的是字符串吗?
-
您可以对列表中的每个项目使用
Select方法 -
事情是:
List<object>不是List<string>。并且请在将来包含代码作为您的问题中的文本。你可以但是创建一个List<string>通过OfType<string>() -
@madoxdev,是的,它们都是字符串。
标签: c#