Are implicit operators and TypeConverters equivalent?

前端 未结 4 2514
傲寒
傲寒 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

提交回复
热议问题