Are implicit operators and TypeConverters equivale

2020-07-05 17:16发布

问题:

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 the framework (see anything that extends FrameworkElement).

But why? Wouldn't it have been much easier to create string->object and object->string implicit operators and take advantage of those in serialization (both XML and XAML)?

Is it YAGNI? Single responsibility? Because you can't specify operator overloads in interfaces?

回答1:

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



回答2:

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



回答3:

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.



回答4:

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.