如果你愿意使用 / 符号以外的东西,最简单的方法是在 Double 上定义一个扩展方法:
Module DoubleExtensions
<System.Runtime.CompilerServices.Extension()>
Public Function Div(value1 As Double, value2 As Double) As Double
Return Math.Round(value1 / value2, 3)
End Function
End Module
这使您的代码看起来像:
Private Sub Test()
Dim x As Double = 1
Dim y As Double = 3
Dim z As Double = x.Div(y)
Debug.WriteLine(z)
End Sub
否则,因为您不能从基本数据类型继承,您必须创建一个包含您需要支持的所有运算符的类。
这种方法的问题是您必须将这些值声明为新的类类型并实例化它们。以下是一个基本不完整的示例,但说明了您必须做的工作以及之后代码的“外观”:
Public Class MyDouble
Private m_Double As Double
Public Sub New(value As Double)
m_Double = value
End Sub
Public Shared Operator =(value1 As MyDouble, value2 As Double) As Double
value1.Value = value2
Return value2
End Operator
Public Shared Operator <>(value1 As MyDouble, value2 As Double) As Double
Return value2
End Operator
Public Shared Operator /(value1 As MyDouble, value2 As MyDouble) As Double
Return Math.Round(value1.Value / value2.value, 3)
End Operator
Public Property Value As Double
Get
Return m_Double
End Get
Set(value As Double)
m_Double = value
End Set
End Property
End Class
结果代码:
Dim x As New MyDouble(1)
Dim y As New MyDouble(3)
Dim z As Double = x / y