C# 为什么我不能在C中将List转换为List?
代码: 我知道如何避免这种情况,但我想了解根本原因 假设列表中填充了字符串对象,则可以执行以下操作:C# 为什么我不能在C中将List转换为List?,c#,C#,代码: 我知道如何避免这种情况,但我想了解根本原因 假设列表中填充了字符串对象,则可以执行以下操作: 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]'. So
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
强制转换运算符和OfType运算符之间的差异:
C中的Cast操作符将尝试将源序列中存在的所有元素强制转换为指定的类型。如果源序列中的任何元素都不能转换为指定的类型,那么它将抛出InvalidCastException
另一方面,C中的OfType运算符只返回指定类型的元素,源序列中的其余元素将被忽略并从结果中排除
这里可以找到更多的解释:这些对象真的是字符串吗?您可以对列表中的每个项目使用Select方法。事实是:列表不是列表。请在将来的问题中包含代码作为文本。但是,您可以通过@madoxdev从中创建一个列表,是的,它们都是字符串。很好,您同时提到了.Cast和.OfType,但是提到它们之间的区别可能会很有用。感谢您的解决方案和详细解释。但我真的很想知道为什么我不能直接将列表强制转换为列表,即使其中的所有元素都是字符串。@Guosen-仅仅因为两种类型表现出特定的继承关系,这并不意味着由这两种类型参数化的泛型类型表现出相同的继承关系。列表不是从列表中派生出来的。@Damien_不信者,我明白了,非常感谢。
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
List<object> someStrings = new List<object> {"string1", "string2"};
List<string> afterCast = someStrings.Cast<string>().ToList();
List<string> otherOption = someStrings.OfType<string>().ToList();