Are implicit operators and TypeConverters equivalent?

Deadly 提交于 2019-12-04 01:52:24

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

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).

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!