How to make a class-instance accept parameters?

烈酒焚心 提交于 2019-12-25 09:04:00

问题


I wonder if there is a way to make a class instance that accepts parameters and generate results according to this parameter.

This is very common in VB.net built-in classes, but I wonder how to make it myself

Dim myNumbers as new NUMBERS
myNumbers.First = 1
myNumbers.Second = 2
Msgbox(myNumbers(1,2,3,4,5,5).max)

In the above code myNumber is a class which accepts some numbers and return the max.


回答1:


You can use Default properties in order to achieve that. If you don't want it to be Set-able you can just mark it as ReadOnly, and if you don't want to return a specific value just return Nothing.

Returning something from the property:

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

Returning nothing:

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

Usage example:

'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")

The only backside with this is that you must do something with the returned value (for instance assign it to a variable). Simply doing:

myNumbers(64, "Hello World!")

doesn't work.



来源:https://stackoverflow.com/questions/42650871/how-to-make-a-class-instance-accept-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!