开发者

Why Enumerable.Cast raises an InvalidCastException?

If I can implicitly cast an integer value to a double, like:

int a = 4;    
double b = a;
// now b holds 4.0

Why can I not do this:

int[] intNumbers = {10, 6, 1, 9};    
double[] doubleNumbers2 = intNumber开发者_运维百科s.Cast<double>().ToArray();

I get a "Specified cast is not valid" InvalidCastException exception.

Doing the opposite (casting from double to int) results in the same error.

What am I doing wrong?


Well, you have incorrect expectations of Cast, that's all - it's meant to deal with boxing/unboxing, reference and identity conversions, and that's all. It's unfortunate that the documentation isn't as clear as it might be :(

The solution is to use Select:

doubleNumbers2 = intNumbers.Select(x => (double) x).ToArray();


To add to Jon's answer cast is mainly useful for objects that implement IEnumerable but nothing else. Take XmlNodeList for example. If you don't have the luxury of using System.Xml.Linq namespace you can use Cast<XmlElement> to write some nice LINQ queries against it.

var result = xmlNodeList
    .Cast<XmlElement>()
    .Select(e=> e.GetAttribute("A") + e.GetAttribute("B"))
    .ToArray();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜