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

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

问题描述


可能重复:

Puzzling Enumerable.Cast InvalidCastException

您好,

我只是注意到一些很奇怪的 Enumerable.Cast< T> 扩展方法...似乎它不能从 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.

以下代码失败,

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

但是我假设这个代码是等价的, p>

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);
        }

任何人都可以解释这种行为吗?我看了用反射器的Cast方法的代码,但是Reflector不能插入迭代器块,所以很难理解...

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;

我们可以使用以下代码来模拟:

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;
}

这里的关键是,在cast的点,它是一个对象。不是一个int。此操作失败,因为我们只能将对象从对象移除到我们想要的确切类型。我们将从对象 - 这可能是一个盒子长,但它不是。它是一个boxed int。 Eric Lippert在他的博客上讨论了这个问题

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:


我们已决定取消封箱只能取消确定类型。如果你想调用slow方法做所有的goo,它可用 - 你总是可以调用Convert ...

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...

代码,工作,你不是处理一个boxed 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转换为long,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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