且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

How to: Define a Conversion Operator [msdn]

更新时间:2022-09-21 13:11:13

because of my project, learned something about VB.NET. and now by chance, find this stuff. it's pretty cool.

Visual Studio 2005

 

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 IntegerDouble, or String).

Define the type conversion as a CType Function procedure within the class or structure. All conversion procedures must be Public Shared, and each one must specify either Widening or Narrowing.

Defining an operator on a class or structure is also called overloading the operator.

Example

The following example defines conversion operators between a structure called digit and a Byte.

How to: Define a Conversion Operator [msdn]
Public Structure digit
Private dig As Byte
Public Sub New(ByVal b As Byte)
If (b < 0 OrElse b > 9) Then Throw New _
System.ArgumentException("Argument outside range for Byte")
Me.dig = b
End Sub
Public Shared Widening Operator CType(ByVal d As digit) As Byte
Return d.dig
End Operator
Public Shared Narrowing Operator CType(ByVal b As Byte) As digit
Return New digit(b)
End Operator
End Structure

You can test the structure digit with the following code.

How to: Define a Conversion Operator [msdn]
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))
Try
Dim d4 As digit
d4 = CType(CType(d1, Byte) + CType(d2, Byte), digit)
Catch e4 As System.Exception
s &= vbCrLf & "4 + 7 generates " & """" & e4.Message & """"
End Try
Try
Dim d5 As digit = CType(CByte(10), digit)
Catch e5 As System.Exception
s &= vbCrLf & "Initial 10 generates " & """" & e5.Message & """"
End Try
MsgBox(s)
End Sub

 

欢迎加群互相学习,共同进步。QQ群:iOS: 58099570 | Android: 572064792 | Nodejs:329118122 做人要厚道,转载请注明出处!







本文转自张昺华-sky博客园博客,原文链接:http://www.cnblogs.com/sunshine-anycall/archive/2010/12/22/1913789.html,如需转载请自行联系原作者