允许数学在我班级的实例上发生

时间:2010-11-27 05:29:17

标签: .net vb.net operator-overloading

是否有一些我可以实现的接口允许基本比较和数学发生,因为它是一个整数?

例如,假设我有以下课程:

Public Class Something
    Public SomeBigNumber as UInt64
End Class

我想做这样的事情:

Dim SomethingA, SomethingB, SomethingC as New Something

....

If (SomethingA-SomethingB) > SomethingC Then
    'Do stuff
End If

我希望能够实现一些接口(如果它甚至是正确的术语),如果可能的话,它将返回类中包含的UInt64以进行比较和数学。

思考?提前谢谢!

1 个答案:

答案 0 :(得分:4)

您要做的事情称为"operator overloading",它允许您为复杂类型定义比较和数学运算符(如您的类Something)。

例如,您可以在Something类中重载加法和减法运算符,如下所示:

Public Shared Operator +(ByVal val1 As Something, ByVal val2 As Something) As Something
    ''#(calculate the sum of the two specified values)
    Return New Something(val1.SomeBigNumber + val2.SomeBigNumber)
End Operator

Public Shared Operator -(ByVal val1 As Something, ByVal val2 As Something) As Something
    ''#(calculate the difference of the two specified values)
    Return New Something(val1.SomeBigNumber - val2.SomeBigNumber)
End Operator

然后您可以编写如下代码:

Dim newValue As Something = something1 + something2


您也可以以几乎完全相同的方式重载比较运算符(大于,小于,等于和介于两者之间):

Public Shared Operator >(ByVal val1 As Something, ByVal val2 As Something) As Boolean
    ''#(return True if the first value is larger, False otherwise)
    Return (val1.SomeBigNumber > val2.SomeBigNumber)
End Operator

Public Shared Operator <(ByVal val1 As Something, ByVal val2 As Something) As Boolean
    ''#(return True if the first value is smaller, False otherwise)
    Return (val1.SomeBigNumber < val2.SomeBigNumber)
End Operator

允许您编写如下代码:

If something1 > something2 Then
    MesssageBox.Show("The first value is larger.")
Else
    MessageBox.Show("The second value is larger.")
End If

但请注意,其中一些运算符必须在中重载。具体做法是:

  • =<>
  • ><
  • >=<=
  • IsTrueIsFalse