VB.NET编程语言中的运算符操作对于一个程序开发来说起了非常重要的作用。我们在学习的过程中需要加强对这方面的注意,掌握好这些基础知识,才能更好的运用这门语言帮助我们实现程序的开发。#t#
如果已定义了类或结构,则可以定义类或结构的类型与其他数据类型(如 Integer、Double 或 String)之间的VB.NET转换运算符。
将类型转换定义为类型或结构中的 CType 函数过程。所有转换过程必须为 Public Shared,并且每个转换过程必须指定 Widening 或 Narrowing。
在类或结构上定义一个运算符也称为“重载”该运算符。
VB.NET转换运算符示例
下面的示例定义名称为 digit 的结构与 Byte 之间的转换运算符。
Visual Basic
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
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
可以使用下面的代码测试结构 digit。
Visual Basic
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
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
VB.NET转换运算符相关使用技巧就为大家介绍到这里。