困惑Enumerable.Cast InvalidCastException的 [英] Puzzling Enumerable.Cast InvalidCastException

查看:128
本文介绍了困惑Enumerable.Cast InvalidCastException的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面抛出 InvalidCastException的

IEnumerable<int> list = new List<int>() { 1 };
IEnumerable<long> castedList = list.Cast<long>();
Console.WriteLine(castedList.First());

为什么?

我在使用Visual Studio 2008 SP1。

I'm using Visual Studio 2008 SP1.

推荐答案

这是非常奇怪的!有一个博客文章<一个href="http://blogs.msdn.com/ed_maurer/archive/2008/02/16/breaking-change-in-linq-queries-using-explicitly-typed-range-variables.aspx">here它描述了如何的行为演员LT; T&GT;()之间的.NET 3.5和.NET 3.5 SP1,但它仍然无法解释InvalidCastException的,改变你连得到,如果你重写你的code是这样的:

That's very odd! There's a blog post here that describes how the behaviour of Cast<T>() was changed between .NET 3.5 and .NET 3.5 SP1, but it still doesn't explain the InvalidCastException, which you even get if you rewrite your code thus:

var list = new[] { 1 };
var castedList = from long l in list select l;
Console.WriteLine(castedList.First());

显然,你可以解决它通过自己做投

Obviously you can work around it by doing the cast yourself

var castedList = list.Select(i => (long)i);

这个工作,但它并没有在首位解释错误。我试图铸造列表中短期和浮动以及抛出同样的异常。

This works, but it doesn't explain the error in the first place. I tried casting the list to short and float and those threw the same exception.

修改

这一篇博客文章没有解释为什么这是行不通的!

That blog post does explain why it doesn't work!

演员LT; T&GT;()的IEnumerable ,而不是的IEnumerable℃的扩展方法; T&GT; 。这意味着,每个值到达那里它被投点的时候,它已经被装箱回一个System.Object的。从本质上讲它试图做到这一点:

Cast<T>() is an extension method on IEnumerable rather than IEnumerable<T>. That means that by the time each value gets to the point where it's being cast, it has already been boxed back into a System.Object. In essence it's trying to do this:

int i = 1;
object o = i;
long l = (long)o;

这code抛出你得到InvalidCastException的。如果您尝试直接投一个int为长你很好,但铸造装箱的int回长时间不能正常工作。

This code throws the InvalidCastException you're getting. If you try to cast an int directly to a long you're fine, but casting a boxed int back to a long doesn't work.

当然是一个怪胎!

这篇关于困惑Enumerable.Cast InvalidCastException的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆