Are implicity/explicit conversion methods inherited in C#?

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

    The conversion/operator methods are a convenience but as others have noted, they're not always going to do what you want. Particularly, if the compiler doesn't see the right types on both sides of the = sign, it won't even consider your conversion/operator. This is why if you do the following you get a compiler warning:

    object str = "hello";
    if ( str == "hello" ) {
    }
    

    Furthermore, custom conversions are not considered when using the as/is keywords.

    When thinking about implementing an explicit/implicit conversion, you should also consider implementing IConvertible and/or implementing a TypeConverter. This gives you a lot more flexibility when having a base class handle type conversions.

提交回复
热议问题