Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

.net - Is there a way to define an implicit conversion operator in VB.NET?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In VB.NET, use the Widening CType operator to create an implicit conversion:

Class C1
    Public Shared Widening Operator CType(ByVal p1 As C1) As C2

    End Operator
End Class

The opposite, an explicit conversion, can be done by swapping Narrowing for Widening in the above definition.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...