我可以使用显式运算符来创建派生类吗?

Bud*_*dda 2 .net c# inheritance explicit

class Base
{
}

class Derived1 : Base
{
}

class Derived2 : Base
{
    public static explicit operator Derived1(Derived2 d2)
    {
        return new Derived1();
    }
}

class Test
{
    static void Main()
    {
        Base bd2 = new Derived2();

        Derived1 d2ConvertedD1 = (Derived1)bd2; //throws InvalidCastException

    }
}
Run Code Online (Sandbox Code Playgroud)

Unable to cast object of type 'ConsoleApplication1.Derived2' to type 'ConsoleApplication1.Derived1'.

为什么?我的运营商转换有什么问题?

Jon*_*eet 10

麻烦的是,您的自定义转换不被使用,因为编译时类型bd2Base,没有Derived2.编译器甚至没有考虑你的自定义转换,所以它只包括一个正常的转换 - 由于显而易见的原因而失败.(我假设你理解失败,否则你不会创建自定义转换开始.)

编译器根据操作数的编译时类型选择运算符和转换.

虽然你可以先演员Derived2或改变声明bd2,但我会亲自改变大头钉,再看看大局.你想做什么,为什么?Base例如,虚拟方法会更有意义吗?


bjo*_*ars 5

您只能在层次结构中上下编译类,而不能跨越.