为什么下面的不能转换成功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/