Are implicity/explicit conversion methods inherited in C#?

后端 未结 6 2412
春和景丽
春和景丽 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:44

    The reason

    Derived d = (int)3;
    

    does not work is because the type Derived does not exactly match the return value of the operator Base as is required to invoke this operator. Notice that you haven't provided any conversion operators that contain the code new Derived(...), so it is not surprising that you can't make new Derived instances this way.

    Note, however, that the opposite conversion

    Derived v = ...;
    string s = (string)v;
    

    will work fine (as if it were "inherited", although this is not really inheritance due to the static keyword).

提交回复
热议问题