我想知道是否有办法让类实例接受参数并根据此参数生成结果。
这在VB.net内置类中非常常见,但我想知道如何自己创建
Dim myNumbers as new NUMBERS
myNumbers.First = 1
myNumbers.Second = 2
Msgbox(myNumbers(1,2,3,4,5,5).max)
在上面的代码中,myNumber
是一个接受一些数字并返回最大值的类
答案 0 :(得分:0)
您可以使用Default
properties来实现这一目标。如果您不希望它为Set
- 您可以将其标记为ReadOnly
,如果您不想返回特定值,则返回Nothing
。
从酒店返回一些内容:
Default Public ReadOnly Property Calculate(ByVal a As Integer, ByVal b As Integer, ByVal c As Integer) As Integer
Get
Dim d As Integer = a * b + c + Me.First
DoSomeStuff(d)
Return d * Me.Second
End Get
End Property
什么都不做:
Default Public ReadOnly Property Calculate(ByVal a As Integer, ByVal b As String) As Object
Get
Dim c As String = DoStuff()
DoSomeOtherStuff(a, b, Me.First, Me.Second, c)
Return Nothing
End Get
End Property
用法示例:
'With return value.
Dim num As Integer = myNumbers(34, 5, 13)
'Ignoring return value.
Dim dummy As Object = myNumbers(64, "Hello World!")
'Ignoring return value.
Dim dummy As Object = myNumbers.Calculate(13, "I am text")
唯一的缺点是你必须对返回的值做一些事情(例如将其分配给变量)。只需做:
myNumbers(64, "Hello World!")
不起作用。