自定义用户数据类型vb.net - lika double

时间:2013-11-03 21:53:16

标签: .net vb.net types

是否有可能使自定义数据类型如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

1 个答案:

答案 0 :(得分:4)

如果您愿意使用/符号以外的其他内容,最简单的方法是在Double上定义Extension Method

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

否则,因为您无法从基础数据类型继承,所以您必须创建一个包含您需要支持的所有operators的类。

这种方法的问题是你必须将值声明为新的类类型并实例化它们。以下是一个基本上不完整的示例,但说明了您之后必须完成的工作以及代码的“外观”:

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