2010-11-27 42 views
1

是否有一些接口可以实现,以允许基本比较和数学运算,因为它是一个整数?允许在我的类的实例上发生数学问题

例如,假设我有下面的类:

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用于比较和数学运算。

想法?提前致谢!

回答

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
+0

这是我在过去的两年读过的最有用的信息回答周。谢谢科迪!你坚定地回答了我的问题。 – Brad 2010-11-27 06:08:07

相关问题