How often do you create implicit conversions for your classes?
I've been developing .NET applications for 4 years. So far, I did not need to create any implicit conversions for the classes I authored.
Could you provide real-life situations when you could not do without creating implicit conversions?
Thank you
Implicit conversions should only be defined when the type can be converted to or from (preferably to and from) another type with no loss of data. Another criterion is that implicit conversions should be fairly inexpensive, because the developer using your class probably won't be aware of when the implicit conversions are happening.
One example: conversion between coordinate systems. A polar coordinate vector that can convert to cartesian coordinates, for example, might be convenient. However, due to floating point round off it would still be better to leave this as an explicit conversion so that the programmer has to typecast to force the conversion.
Implicit conversion may be warranted if you have two data types that store data in the same format but the only distinction between the types is semantic - how they are used or what they mean. Real world example: Conversion between datetime data types that have the same (or compatible) underlying representation but differ only in epoc start date. You'll find these when migrating older codebases to newer frameworks where both define a datetime type but the semantics are slightly different. Implicit conversion here (assuming there is no data loss at all) is probably ok and a good idea.
If you have a set of types and you have defined your own rules for how the types can be converted between each other, then some of those conversions may be implicit and some explicit depending on the "severity" of the conversion. The primary instance of where I've used implicit conversion when implementing a class in .NET was when I was implementing Win32 Variant semantics for the Delphi runtime library. Win32 and the Delphi language specify a number of conversions on Variant data that can be done implicity.
That you have not found a need to create implicit conversions is actually a good thing. Just because you can doesn't mean you should. Implicit conversions exist in .NET primarily to allow different programming languages to represent their own semantics in a way that should be interoperable and understandable by other .NET languages.
链接地址: http://www.djcxy.com/p/45290.html上一篇: 在Django inlineformset中过滤Queryset
下一篇: 你多久创建一次隐式转换?