Are implicity/explicit conversion methods inherited in C#?

后端 未结 6 2416
春和景丽
春和景丽 2021-02-15 16:00

I\'m not sure what I\'m doing wrong here. I have a generic class, which is basically a glorified integer, with a few methods for certain string formatting, as well as into/from

6条回答
  •  遥遥无期
    2021-02-15 16:41

    No, it will not work that way. The compiler will not implicitly downcast from a base to a derived for you. Basically, you can't do ...

    D d = new B();
    

    You will get your base class implmentations from your string cast, because it will do the implicit upcasting for you.

    You could do a work around if you didn't want to copy your methods to your derived class with an extension function on integers, like (assuming your derived class is called D) ...

    public static class Ext
    {
        public static D IntAsD(this int val)
        {
            return new D(val);
        }
    }
    

    Then, you could do what you want with ...

    D d1 = 5.IntAsD();
    

    Granted, it's not perfect, but it might fit your needs.

提交回复
热议问题