Are implicit operators and TypeConverters equivalent?

前端 未结 4 2513
傲寒
傲寒 2021-02-20 09:57

It seems to me its very easy to implement an implicit operator versus a TypeConverter, so I\'m assuming they aren\'t equivalent because of the prevalence of TypeConverters in th

相关标签:
4条回答
  • 2021-02-20 10:31

    Type converters are a lot more complex than they seem; a type-converter has access to a range of meta-data about the context of the conversion - for example, the property and object that are involved. This is used to provide custom options per scenario (think: linked drop-downs, i.e. Country / County / City / etc). You can also specify the type-converter on a per-property basis, which I use in lots of places to provide different handling of various string properties. An operator would treat all strings identically.

    An implicit operator only knows about the value that is being converted, but has far greater compile-time support.

    Or another way: TypeConverter is a framework feature with framework support; operators are (primarily) a language feature with language support

    To add more - type-converters (despite the name) don't just convert:

    • they provide sub-property metadata (think: expanding properties on PropertyGrid)
    • they suggest available options for a type (think: drop-down choices on PropertyGrid)

    Note they are used in more places than just PropertyGrid, though ;-p

    0 讨论(0)
  • 2021-02-20 10:31

    I am no expert on this.

    But at first glance, it looks like - you can provide converters outside of the original class (as against implicit operator) & maybe you can define multiple TypeConverter classes for a same thing (if you want to get different views for the same value).

    0 讨论(0)
  • 2021-02-20 10:40

    Just curious: TypeConverters can work with the visual studio designer, such that if you provide the right TypeConverter for a properties like Lists or Arrays you can set them via the designer. Do implicit operators also provide this service? If not, I suspect that answers your question: they're used in the framework so that controls using those items can work with the designer.

    0 讨论(0)
  • 2021-02-20 10:50

    Implicit operators are nice but also they can be confusing. I think that when you need to convert from one type to another it best to be explicit as there is no question as to what is going on.

    Also implicit operators seemed to be reserved for things that are very much alike and the implicit conversion is intuitive. But I guess that is all subjective anyhow, use your best judgement.

    0 讨论(0)
提交回复
热议问题