IEnumerable.Cast没有调用强制转换

Mar*_*eal 2 c# linq casting

我不了解这种方式.Cast有效.我有一个明确的(虽然隐式也失败)演员定义,当我"定期"使用时似乎有效,但当我尝试使用.Cast时却没有.为什么?这是一些可编译的代码,用于演示我的问题.

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();
}
Run Code Online (Sandbox Code Playgroud)

Ree*_*sey 6

Cast<T>功能可以使用IEnumerable,而不是IEnumerable<T>.因此,它将实例System.Object视为您的特定类型.对象上不存在显式转换,因此失败.

为了做你的方法,你应该使用Select()代替:

Class2 c3 = c1.Select(c => (Class2)c).First();
Run Code Online (Sandbox Code Playgroud)