In C#, you can use the implicit keyword to define an implicit user-defined type conversion operator.
In VB.NET, you can define a CType conversion operator that will explicitly convert a user-defined type into another type.
Is there a way to declare an implicit conversion operator in VB.NET?
I can't seem to find any information on this....
Answer
I found my answer in the MSDN documentation for the Widening
operator. Apparently the CType Widening
operator is "called" for implicit conversions whereas the CType Narrowing
operator is called for explicit conversions.
At first, I thought this documentation was incorrect, because I was experiencing an exception during testing. I re-tested and found something very strange. The function I implemented as the widening conversion operator works fine when an implicit cast is done using the "=" operator.
For example, the following will implicitly cast the Something
type into MyClass
. It calls my Widening
conversion implementation correctly and everything works without error:
Dim y As Something
Dim x As MyClass = y
However, if the implicit cast is done in a foreach
loop, it does not work.
For example, the following code will throw an exception ("Unable to cast object of type 'Something' to type 'MyClass'") when the Something
type is implicitly casted to MyClass
in the For Each
loop:
Dim anArrayOfSomethingTypes() As Something = getArrayOfSomethings()
For Each x As MyType In anArrayOfSomethingTypes
....
Next
Any insight on this is greatly appreciated.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…