In my previous example, you were introduced to simple delegates. Now, I shall extend the same with parameters.
To help us understand "delegates with parameters," I added a new class as follows:
Public Class Sample02
Private _x As Integer
Private _y As Integer
Public Sub New()
End Sub
Public Sub New(ByVal a As Integer, ByVal b As Integer)
_x = a
_y = b
End Sub
Public Property X() As Integer
Get
Return _x
End Get
Set(ByVal value As Integer)
_x = value
End Set
End Property
Public Property Y() As Integer
Get
Return _y
End Get
Set(ByVal value As Integer)
_y = value
End Set
End Property
Public Sub Increment(ByVal IncrementValue As Integer)
_x += IncrementValue
_y += IncrementValue
End Sub
Public Sub Add()
MessageBox.Show("Sum = " & (Me.X + Me.Y))
End Sub
Public Sub Multiply()
MessageBox.Show("Product = " & (Me.X * Me.Y))
End Sub
End Class
You can observe that a new method, "Increment" (which accepts a parameter), is added. Let us try to access it using delegate. The following is the code:
'delegate with parameters
Public Class Form4
Delegate Sub Calculate()
Delegate Sub IncreaseValues(ByVal value As Integer)
Dim delegCalc As Calculate
Dim delegIncrease As IncreaseValues
Dim obj As New Sample02(10, 20)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
delegCalc = AddressOf obj.Add
delegIncrease = AddressOf obj.Increment
delegIncrease(100)
delegCalc()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
delegCalc = AddressOf obj.Multiply
delegIncrease = AddressOf obj.Increment
delegIncrease(100)
delegCalc()
End Sub
End Class
Let us try to understand this step by step. Consider the following first:
Delegate Sub IncreaseValues(ByVal value As Integer)
"IncreaseValues" is a delegate type of class now. However, it only accepts methods (which can be executed later) with just one parameter of type integer.
Dim obj As New Sample02(10, 20)
delegIncrease = AddressOf obj.Increment
As the "Increment" method accepts a parameter of type integer, it can be assigned to the delegate object we declared earlier.
Finally, the method gets executed with a value of 100 using the statement:
delegIncrease(100)
A delegate declaration can have multiple parameters, not only one. And further, those parameters could be of any type, from primitive data types to reference types!
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.