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

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

问题描述

可能的重复:
令人困惑的 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.

以下代码失败并出现 InvalidCastException :

The following code fails with an InvalidCastException :

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

但是这段我认为是等效的代码确实有效:

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

谁能解释这种行为?我用Reflector看了一下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...

推荐答案

Cast 中的相关行:

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

这也失败了.这里的关键是,在转换点,它是一个对象.不是整数.这失败了,因为我们只能从一个对象拆箱到我们想要的确切类型.我们从对象出发 - 这可能是一个盒装的长,但事实并非如此.这是一个装箱的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:

我们决定拆箱只能拆箱到确切的类型.如果您想调用执行所有这些操作的慢速方法,它是可用的——您可以随时调用 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...

在您运行的代码中,您处理的不是装箱的 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天全站免登陆