我不理解有關方式的一些東西.Cast的作品。我有一個明確的(雖然隱含也失敗)轉換定義,這似乎工作時,我經常使用它,但不是當我嘗試使用.Cast。爲什麼?這裏有一些可以編譯的代碼來演示我的問題。IEnumerable.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();
}
相關(如果不重複):http://stackoverflow.com/questions/445471/puzzling-enumerable-cast- invalidcastexception – 2010-06-08 22:56:46