c# - 为什么从 IEnumerable<string> 转换为 List<string> 会失败?

标签 c# linq casting classcastexception

为什么下面的不能转换成功IEnumerable<string>List<string>

var l = new List<Tuple<string, int>>();
l.Add(new Tuple<string, int>("a string", 1));
List<string> s = (List<string>)l.Select(x => x.Item1); // System.InvalidCastException
MessageBox.Show(s[0]);

另外,为什么在 Visual Studio 中没有正确捕获异常?它出现在调试窗口中,但不会停止程序的执行。

最佳答案

Select返回 IEnumerable<T> .如果您希望结果为 List<T> ,使用:

List<string> s = l.Select(x => x.Item1).ToList()

内部Select方法生成List根本;这些元素作为 IEnumerable<T> 即时返回被迭代。

我会排除被捕获的异常。我的猜测是您有一个捕获物(可能不是您添加的捕获物)正在沿途的某个地方捡起它。

关于c# - 为什么从 IEnumerable<string> 转换为 List<string> 会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14411972/

相关文章:

c++ - 在 C/C++ 中将 int 转换为 bool

c# - 在不使用数组的情况下,我可以更快地查看特定索引吗?

c# - Discord Bot (C#) 加入语音 channel 时遇到问题

c# - 如何避免窗体上出现大量用户控件

Linq 相当于 SQL LEFT 函数?

MySQL 意外结果 : "IN"-clause (number, 'string' ) 在 varchar 列上

c - printf 为 float 指定整数格式字符串

c# - 用于将 Java 的 JSON 与 C# 相互转换的映射工具

c# - 将列值作为 IEnumerable 返回

C# 使用组选择重复项