本文共 1899 字,大约阅读时间需要 6 分钟。
because of my project, learned something about VB.NET. and now by chance, find this stuff. it's pretty cool.
If you have defined a class or structure, you can define a type conversion operator between the type of your class or structure and another data type (such as Integer, Double, or String).
Define the type conversion as a procedure within the class or structure. All conversion procedures must be Public Shared, and each one must specify either or .
Defining an operator on a class or structure is also called overloading the operator.
The following example defines conversion operators between a structure called digit and a Byte.
Public Structure digitPrivate dig As BytePublic Sub New(ByVal b As Byte)If (b < 0 OrElse b > 9) Then Throw New _System.ArgumentException("Argument outside range for Byte")Me.dig = bEnd SubPublic Shared Widening Operator CType(ByVal d As digit) As ByteReturn d.digEnd OperatorPublic Shared Narrowing Operator CType(ByVal b As Byte) As digitReturn New digit(b)End OperatorEnd Structure
You can test the structure digit with the following code.
Public Sub consumeDigit()Dim d1 As New digit(4)Dim d2 As New digit(7)Dim d3 As digit = CType(CByte(3), digit)Dim s As String = "Initial 4 generates " & CStr(CType(d1, Byte)) _& vbCrLf & "Initial 7 generates " & CStr(CType(d2, Byte)) _& vbCrLf & "Converted 3 generates " & CStr(CType(d3, Byte))TryDim d4 As digitd4 = CType(CType(d1, Byte) + CType(d2, Byte), digit)Catch e4 As System.Exceptions &= vbCrLf & "4 + 7 generates " & """" & e4.Message & """"End TryTryDim d5 As digit = CType(CByte(10), digit)Catch e5 As System.Exceptions &= vbCrLf & "Initial 10 generates " & """" & e5.Message & """"End TryMsgBox(s)End Sub