为什么我会收到InvalidCastException的? [英] Why am I getting InvalidCastException?

查看:113
本文介绍了为什么我会收到InvalidCastException的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#下面的代码片段

I have following code snippet in c#

List<int> list = new List<int>() { 1, 23, 5, 3, 423, 3 };
            var query = list.Cast<double>().Select(d => d);
            try
            {
                foreach (var item in query)
                {
                    Console.WriteLine(item);

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);

            }



这是编译完美,但是当我执行这个我越来越例外。

It's compile perfectly,but when i am executing this I am getting exception.

推荐答案

由于您是从一个int类型转换翻一番,这不是它的一个类型转换转换,这是从当你施放INT在一般情况下翻番有所不同

Because you're typecasting from an int to double, it's not a conversion it's a type cast and this is somewhat different from when you cast int to double in the general case.

演员LT; T> 扩展方法的用途在IL指令 unbox.any

The Cast<T> extension method uses the IL instruction unbox.any

尽管C#铸像这样

var x = (double)42;



实际上会导致IL指令

Actually results in the IL instruction

conv.r8 

从根本上拆箱的类型,不同的类型错了,这就是为什么你得到的异常。

Fundamentally unboxing an type as a different type is wrong and that's why you get the exception.

这个问题有相同的答案,并链接到的博客文章通过埃里克利珀。

This question has the same answer and also links to a blog post by Eric Lippert.

这篇关于为什么我会收到InvalidCastException的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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