我有以下类的示例结构:
public class Base
{
}
public class Child1 : Base
{
}
public class Child2 : Base
{
}
我想做一些黑魔法:
Base @base = new Child2(); //note: there @base is declared as Base while actual type is `Child2`
var child1 = (Child1) @base;
System.InvalidCastException
它按预期失败了。
然后我将隐式转换运算符添加到Child2
:
public class Child2 : Base
{
public static implicit operator Child1(Child2 child2)
{
return new Child1();
}
}
并且代码仍然抛出相同的异常(显式运算符也无济于事)。
您是否有任何想法如何在不使用dynamic
自定义转换方法或将局部变量声明@base
为的情况下解决此问题Child2
?