开发者

IEnumerable.Cast not calling cast overload

I'm not understanding something about the way .Cast works. I have an explicit (though implicit also fails) cast defined which 开发者_如何转开发seems to work when I use it "regularly", but not when I try to use .Cast. Why? Here is some compilable code that demonstrates my problem.

public class Class1
{
    public string prop1 { get; set; }
    public int prop2 { get; set; }

    public static explicit operator Class2(Class1 c1)
    {
        return new Class2() { prop1 = c1.prop1, prop2 = c1.prop2 };
    }
}

public class Class2
{
    public string prop1 { get; set; }
    public int prop2 { get; set; }
}

void Main()
{
    Class1[] c1 = new Class1[] { new Class1() {prop1 = "asdf",prop2 = 1}};

    //works
    Class2 c2 = (Class2)c1[0];

    //doesn't work: Compiles, but throws at run-time
    //InvalidCastException: Unable to cast object of type 'Class1' to type 'Class2'.
    Class2 c3 = c1.Cast<Class2>().First();
}


The Cast<T> function works on IEnumerable, not IEnumerable<T>. As such, it's treating the instances as System.Object, not as your specific type. The explicit conversion does not exist on object, so it fails.

In order to do you method, you should use Select() instead:

Class2 c3 = c1.Select(c => (Class2)c).First();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜