Are implicity/explicit conversion methods inherited in C#?

后端 未结 6 2588
春和景丽
春和景丽 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条回答
  •  萌比男神i
    2021-02-15 16:24

    Overloaded operators (including conversions) are inherited, but not in a way you seemingly expect them to. In particular, they aren't magically extended to operate on derived types. Let's look at your code again:

    Derived d = 3;
    

    At this point the compiler has two classes to work with, System.Int32, and Derived. So it looks for conversion operators in those classes. It will consider those inherited by Derived from Base, namely:

    public static implicit operator Base(int Value);
    public static explicit operator string(Base Value);
    

    The second one doesn't match because the argument should be an Int32. The first one does match the argument, but then it's return type is Base, and that one doesn't match. On the other hand, you can write this:

    string s = (string) new Derived();
    

    And it will work, because the explicit operator in Base exists and is applicable (argument is expected to be Base, Derived inherits from Base and therefore matches the argument type).

    The reason why the compiler won't automagically redefine conversion operators in derived types "properly" is because there's no generic way to do so.

提交回复
热议问题