Why Enumerable.Cast raises an InvalidCastException?

前端 未结 2 923
名媛妹妹
名媛妹妹 2020-11-27 06:49

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:

2条回答
  •  孤城傲影
    2020-11-27 07:15

    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 to write some nice LINQ queries against it.

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

提交回复
热议问题