1

是否有机会制作自定义定义的数据类型,如 double 但其中包含圆形功能。

例如:

Dim x, y, z as Double
x = 10
y = 3
z = 10 / 3
Result.>  z = 3.333333

如何创建一个默认数据类型,该数据类型将自动将值舍入为预定义的小数。但不适用于 z.math 或 math(z) 等函数

像 :

Dim x,y,z as CustomType
x = 10
y = 3
z = 10 / 3

因为我们创建了自定义数据类型,我们知道它将在小数点后三位四舍五入,结果将是:z = 3.330

4

1 回答 1

4

如果你愿意使用 / 符号以外的东西,最简单的方法是在 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
于 2013-11-03T22:52:08.630 回答