Enumerable.Cast< T>扩展方法不能从int转换为长,为什么呢? [英] Enumerable.Cast<T> extension method fails to cast from int to long, why?

查看:194
本文介绍了Enumerable.Cast< T>扩展方法不能从int转换为长,为什么呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/445471/puzzling-enumerable-cast-invalidcastexception\">Puzzling Enumerable.Cast InvalidCastException的

我刚刚发现了一些用很奇怪的 Enumerable.Cast&LT; T&GT; 扩展方法...看来,它不能从投INT ,即使这个转换是合法的。

I just noticed something quite strange with the Enumerable.Cast<T> extension method... It seems that it can't cast from int to long, even though this cast is perfectly legal.

以下code不能与 InvalidCastException的

        foreach (var item in Enumerable.Range(0,10).Cast<long>())
        {
            Console.WriteLine(item);
        }

但是,这code,我认为是等价的,没有工作:

But this code, which I assumed to be equivalent, does work :

        foreach (var item in Enumerable.Range(0,10).Select(i => (long)i))
        {
            Console.WriteLine(item);
        }

任何人能解释这种行为?我看着与反射铸造法的code,但反射不能跨$ P $私人迭代器块,所以它的pretty费解...

Can anyone explain that behavior ? I looked at the code of the Cast method with Reflector, but Reflector can't interprete iterator blocks, so it's pretty hard to understand...

推荐答案

在相关行演员

 this.<>2__current = (TResult)this.<obj>5__ab;

我们可以使用下面的code模仿这种

We can mimic this using the following code:

int foo = 1;
long bar = Cast<long>(foo); //oh noes!

T Cast<T>(object input)
{
    return (T)input;
}

这也将失败。这里的关键是,在浇铸的角度来看,它是一个对象。不是int。失败的原因,我们只能从拆箱对象到的确切类型的我们想要的。我们正从对象去 - 这可能是一个漫长盒装,但事实并非如此。这是装箱的int。 埃里克利珀讨论了这个在他的博客

Which also fails. The key here is that at the point of cast, it's an object. Not an int. This fails because we can only unbox from an object to the exact type we want. We are going from object - which could be a boxed long, but it's not. It's a boxed int. Eric Lippert discussed this on his blog:

我们已经决定,拆箱只能拆箱的确切类型。如果你想打电话,做所有的感伤,这是可用的慢方法 - 你可以随时调用转换...

we’ve decided that unboxing can only unbox to the exact type. If you want to call the slow method that does all that goo, it’s available – you can always call Convert...

在您的code这工作,你不处理装箱的int(对象),你有一个int。

In your code which works, you're not dealing with a boxed int (an object), you've got an int.

这篇关于Enumerable.Cast&LT; T&GT;扩展方法不能从int转换为长,为什么呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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