Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
339 views
in Technique[技术] by (71.8m points)

c# - Why am I getting InvalidCastException?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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

While a C# cast like this

var x = (double)42;

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...