VB.net study notes (23) re-knowledge entrusted

Source: Internet
Author: User


First, call the static method
1. Statement
A delegate must use a pre-declaration definition, which can have parameters (one or more), and can have a return value.

    ' is located in the Declaration section of a module or class    Delegate Sub oneargsub{byval msg as String ' with one parameter and no return type
A class that defines a delegate. A new class named Oneargsub has been created in the background, and this class inherits from the System.Delegate class. (more accurately, inherited from Systetn.muhicastdelegate, and System.MulticastDelegate is inherited from System.Delegate.) )
2. Instantiation
Once the new class is declared, the delegate object can be instantiated in the function block where the delegate is to be used:
        Dim Deleg as Oneargsub                      ' declaration class        Deleg = New oneargsub (AddressOf displaymsg) ' instantiation of 1: with New        Deleg = AddressOf Displaym SG                ' instantiation 2: direct use of AddressOf
Instantiation is to let B and c establish a connection, through the AddressOf (extract function pointer) to the C method (or function) address assigned to B, so B is the final execution C.
3. Perfect the entrusted thing (C, the process of matching the entrusted signature)
The method (or function) signature of the final perfect delegate must be consistent with the declaration of the first step, and the name matches the name of the method (or function) following the second step AddressOf.
    Private Sub displaymsg (ByVal mes as String) ' with one parameter and no return type        TextBox1.Text = Mes              ' displaymsg with AddressOf Signature    End Sub
4, the implementation of the Commission
When B is connected to C and the code of C is perfected, the Invoke method of the Deleg variable can be called (with parameters, which should be consistent with the declaration).
        Deleg. Invoke ("Lawsuit for Me")    ' execute delegate, parameter type and number should be consistent with declaration
The complete delegation process is as follows:
public class Frmmain    ' is located in the declaration portion of a module or class    Private Delegate Sub oneargsub (ByVal msg as String) ' with one parameter and no return type    Private Sub button1_click (sender as Object, e as EventArgs) Handles Button1.Click        Dim deleg as oneargsub                      ' declaration class        Deleg = new Oneargsub (AddressOf displaymsg) ' Instantiation 1: With new        Deleg. Invoke ("Lawsuit for Me")                  ' execute delegate, parameter type and number should be consistent with declaration    End Sub    Private Sub displaymsg (ByVal mes as String) ' with one parameter and no return type        TextBox1.Text = Mes                    ' displaymsg and AddressOf Signature are the same    end SubEnd Class

Delegates work in the same way as all static methods, which refer to sub and Function procedures in module and shared procedures in classes. The following example uses a delegate to invoke a shared function method in a class:
Public class Frmmain Private Delegate Function askyesnoquestion (ByVal msg as String) as Boolean private Sub button1_click (sender As Object, e as EventArgs) Handles Button1.Click Dim question as askyesnoquestion question = New Askyesnoque Stion (AddressOf Messagedisplayer.askyesno) ' shared method address returns If question ("Do you want to save?")                Then ' is equivalent to calling the shared method in the class AskYesNo, where the Invoke TextBox1.Text = "Saving ..." is useless. Else TextBox1.Text = "Nothing" End If end subend classpublic Class messagedisplayer Shared functio n AskYesNo (ByVal mes as String) as Boolean ' shared method, called by the class name Dim answer as MsgBoxResult answer = MsgBox (MES, MSGB Oxstyle.yesno Or msgboxstyle.question) return (answer = msgboxresult.yes) ' Answer Yes, back to true End functionend CLASS
Invoke for System. The delegate class and all classes inherited from this class are default members, so you can omit it when calling this function. Ultimately, calling a procedure and calling a method through a delegate variable looks similar:
When using delegates, you must be aware of the optional parameters. The procedure to which the delegate is directed can contain the optional and ParamArray parameters, and the delegate will correctly pass the expected number of arguments. This is done even if the target process is overloaded, in which case the delegate can correctly invoke the overloaded version of the procedure. However, the delegate definition itself cannot contain optional or ParamArray parameters.

second, invoke the instance method
Use a delegate on an instantiated object. Because the object's non-shared method cannot access the function address of the method from the class name, only the function address (public) of the method of the object is exposed after the object is instantiated. To use a delegate. So the AddressOf parameter must follow the object that was instantiated earlier.
Public Class frmmain Private Delegate Function askyesnoquestion (ByVal answer As Boolean) As Boolean Private Sub Butt On1_click (sender As Object, E as EventArgs) Handles Button1.Click ' first instantiate object Dim Msgdisp as New messagedisplay Er msgdisp. Msgtext = "What the conversation class is going to show" Msgdisp. Msgtitle = "title of the Conversation class" ' Then, instantiate the delegate Dim question as New askyesnoquestion (AddressOf msgdisp. AskYesNo) ' Execute delegate If question (true) then TextBox1.Text = "Answer true" Else textbox1.te  XT = "answer is false" end If end subend classpublic Class messagedisplayer public msgtext as String public msgtitle        As String Function AskYesNo (ByVal Defaultanser As Boolean) As Boolean ' shared method, called by the class name Dim style as MsgBoxStyle If Defaultanser then style = Msgboxstyle.defaultbutton1 Else style = MSGBOXSTYLE.DEFAULTB Utton2 End If style = style or msgboxstyle.question or Msgboxstyle.yesno Return MsgBox (msgteXT, style, msgtitle) = Msgboxresult.yes End functionend Class 

third, the properties of the delegate
All delegate classes derive from System.Delegate, so they inherit all the properties and methods defined in the base class.
Target Property
Gets the class instance to which the current delegate invokes an instance method. It returns a reference to the object that is the target of the delegate. If the delegate represents an instance method, the object on which the instance method is invoked for the current delegate, or nothing if the delegate represents a static method.
Example: The previous instance question. The result of Target.tostring is: Test.messagedisplayer (because the project name is Test, the class name is Messagedisplayer)
If the delegate points to a shared method, the target method returns a reference to the System.Type object that represents the class. In this case, you need to use the reflection method to extract information about the class itself.
Method Property
Gets the method represented by the delegate. It returns the System.Reflection.Methodlnfo object (which describes the method being called), its attributes, and other information.
Example: The previous instance question. The result of Method.tostring is: Boolean AskYesNo (this is exactly how the delegate is declared)

iv. definition of polymorphic behavior
Delegates have a lot of flexibility when calling. As long as all the called procedures should have the same parameter signature, that is, determine which is called. Examples of the following:
(1) Use a delegate to invoke a method in a static method group: These static methods can be in a module or in a class.
(2) Use delegates to invoke different methods in the same object instance.
(3) Use a delegate to invoke different methods for different objects of the same class.
(4) Use delegates to invoke different methods of objects belonging to different classes.
Example: The following is a program execution log record. The point is that before executing the delegate (log function), the log is associated to which function, you can see that 1 o'clock is associated to the stream, and 2 o'clock is associated to the console. In short, a dynamic association in a program can lead to different ways of execution and results.
Module Module1 Delegate Sub logwriter (ByVal Msg as String) ' declares a delegate type Dim log as LogWriter ' defines a delegate variable (that is, the upper function with one parameter) Dim fw As System.IO.StreamWriter ' defines the rheological amount Sub main () Dim args () as String = Environment.g Etcommandlineargs ' gets the command-line argument If args. Length > 1 Then ' if the command line contains a file name, open this file FW = New System.IO.StreamWriter (args (1)) log = New LogWriter (AddressOf FW.        WriteLine) ' 1, delegate to stream output WriteLine method Else log = New LogWriter (AddressOf Console.WriteLine) ' 2, delegate to console output End if call Dotherealjob () ' 3, the child function only executes the delegate function if not (FW was nothing) the N FW.                              Close () End Sub Sub Dotherealjob () log ("Start of Program.")        ' 4. Execute log here ("in the middle of the program.")    Log ("End of Program.") End SubEnd Module 
Description:Environment.getcommandlineargs returns an array of strings containing the command-line arguments of the current process. What does that mean?
This is actually the same as the C language at the beginning of the same as main, where main can take parameters, but also without parameters, with the parameter: int main (int argc,char *argv[])
The first one is the number of arguments, followed by the array. The parameter value of the main function is obtained from the operating system command line.
When we want to run an executable file, type the file name at the DOS prompt, and then enter the actual parameters to transfer these arguments to the main parameter. For example: The general form of the command line at the DOS prompt is:
c:\> executable file name parameter parameters ...;
For example: Copy D:\1.text E:\3.text (the 1.text file of the D drive is copied to the 3.text of the E drive, the copy is renamed)
The following two are the parameters, the number of 2.

v. Delegation and callbacks
--------------
callback function
When the program runs, typically, the application (application programs) often invokes the pre-prepared functions in the library through the API. However, some library functions require the application to pass it a function, which is called at the appropriate time to accomplish the target task. The passed-in, then-called function is called a callback (callback function).

For example, there is a hotel with wake-up service, but it is required to decide how to wake up. Can be a room phone, or send a waiter to knock on the door, sleep afraid of delay, you can also ask to pour water basin on their head. Here, the "Wake Up" behavior is provided by the hotel, which is equivalent to the library function, but the method of waking up is determined by the traveler and tells the hotel, that is, the callback function. And the traveler tells the hotel how to wake up their actions, that is, the callback function to transfer the function of the functions, called the registration callback function (to register a callback functions).
-------------------
Several Windows API functions use callback mechanisms, such as emnuwindows and enumfonts,enumwindows, to enumerate all the top-level windows in the system and callback the calling program for each window found by the survey.
Declare Function EnumWindows Lib "user32" (ByVal Ipenumfunc as Enumwindows_callback, ByVal LParam As Integer) As Integer
Delegates can be used effectively to receive callback notifications from the Windows API to make them more secure. Delegate to the above callback declaration:
Delegate Function Enumwindows_callback (ByVal hWnd As Integer, ByVal lParam As Integer) As Integer
Then perfect the entrusted thing (method or function):
    Function ENUMWINDOWS_CBK (ByVal hwnd As Integer, ByVal iparam As Integer) As Integer        Console.WriteLine (hwnd) ' Show this top-level window Handle                return 1 ' returns 1, continue enumerating    End Function
The last execution of the delegate can be: EnumWindows (AddressOf enumwindows_cbk, 0)
Full code: (To simplify, show only handles)
Module Module1    Declare Function EnumWindows Lib "user32" (ByVal Ipenumfunc as Enumwindows_callback, ByVal LParam as in Teger) As Integer    Delegate Function enumwindows_callback (ByVal hWnd As Integer, ByVal lParam as Integer) as Integer
   sub Main ()        EnumWindows (AddressOf enumwindows_cbk, 0)        console.read ()    End Sub    Function Enumwindows_ CBK (ByVal hwnd As Integer, ByVal iparam As Integer) As Integer        Console.WriteLine (hWnd) ' shows the handle of this top-level window         Return 1                ' Return 1, continue listing    End FunctionEnd Module

Example: Here is an example of a delegate that can be aborted at any time. The program is a bit complicated, so don't take the recursive process. Only see the use and suspension of the Commission.
Module Module1 Delegate Function TRAVERSEDIRECTORYTREE_CBK (ByVal dirName as String) as Boolean Sub main () Tra Versedirectorytree ("E:\", AddressOf displaydirectoryname) End Sub Function displaydirectoryname (ByVal path as String As Boolean Console.WriteLine (path) If path = "E:\tools\Thunder\Bho" Then ' 3, keep track of this directory Return Tr UE Else Return False End If End Function Sub traversedirectorytree (ByVal path as String, by Val callback as TRAVERSEDIRECTORYTREE_CBK) ' 1, delegate as parameter Dim dirName as String Static nestlevel as Integer ' nesting level Do not Static isCanceled as Boolean ' De-enumeration is true nestlevel + = 1 ' nesting level for each dirName in Sys Tem. Io. Directory.getdirectories (path) isCanceled = callback. Invoke (DirName) ' 2, callback program execution return notification if isCanceled then exit for ' 4, the notification is true (un-enumerating) exits the loop Trav Ersedirectorytree (DirName, callback) ' Otherwise, recursion continues to enumerate Next Nestlevel-= 1 ' exits this nested layer if Nestlevel = 0 Then ' reset isCanceled = False ' If ready to return to the user otherwise the following X-calls are not correct Work End If End SubEnd Module
Description:1 delegates enter in as arguments, at 2 when the delegate is actually invoked, 3 determines the state of the delegate, and 4 depends on the return value of the delegate to determine whether recursion continues.

VI. multi-channel broadcast commissioned Mulltcast
The. NET framework supports two types of delegates:
1. Unicast delegation
A method that uses a unicast delegate to invoke an object. When Invoke () is called in a unicast delegate, the delegate multicast invokes the specified method of the delegated object broadcast.
2. Multicast delegation
A series of methods that use multicast delegates to invoke different objects implicitly. The multicast delegate supports a call list, which method of which object is called by the options in the list. When invoke is called in a multicast delegate, the delegate invokes the specified method of the delegated object sequentially.
A multicast delegate is useful if you need to perform the same action on an object collection, or if you need to perform a series of operations on the same object, or a combination of the above two cases. Use multicast delegates to implicitly form a collection of the objects that need to be performed and those referenced by the execution operation.

the multicast delegate step.:
(1) Define a delegate type: The multicast delegate can only execute methods that have the same signature.
(2) Write a method with the same signature as the delegate.
(3) Create a delegate object and bind the delegate object to the first method that needs to be called through the delegate.
(4) Create another delegate object that binds it to the next method that needs to be called.
(5) Call the Combine method of the System.Delegate class to concatenate the two delegates created above into a comprehensive multicast delegate.
The Combine method returns a new delegate that contains all of the delegates in the invocation list.
(6) Repeat the previous two steps, create the required delegates as needed, and synthesize them as multicast delegates.
(7) If you need to remove a delegate from a multicast delegate, call the Remove method implementation of the System.Delegate class.
The Remove method returns a new delegate that does not contain a delegate that has been removed from the calling table of the delegate. If only the delegate that you just deleted is included in the invocation list, the Remove method returns Nothing.
(8) When calling the method specified by the multicast delegate, simply call the Invoke method as before, call the method in the order of the invocation list, and return the value as the result of the last method in the invocation list.

Example: The main form continually adds a subform and refreshes the background of multiple subforms that have been generated by the multicast delegate at the same time.
Create a subform class, create a subform each time, and add it to the multicast delegate, and once the delegate executes, multiple methods (the subform color) are refreshed at the same time, and once you close a subform, the multicast list moves out of the delegate.
Final effect:

Subform Class (by right-clicking the project in the solution, adding an item--class, to complete)

Public Class childform    Inherits System.Windows.Forms.Form    Private Sub childform_load (ByVal sender as Object, ByVal e as EventArgs) Handles mybase.load        Text = "Created" & DateTime.Now.ToLongTimeString () ' Subform title    End sub
   public Function Repaint (ByVal thecolor as color) as String        BackColor = thecolor                                ' Subform background color        Text = "Updated" & Amp DateTime.Now.ToLongTimeString () ' Subform brush color time        Return me.text    End Function    Protected Sub Childform_cancel ( ByVal sender as Object, ByVal e as EventArgs) Handles mybase.closing        ' Tell the main form we're Closing, so the main Form can ' remove us from its multicast delegate         Dim Myowner as Frmmain = CType (Owner, frmmain)        Myowner.childform Closing (Me)    End subend Class

Main form code:
public class Frmmain Delegate Function mydelegate (ByVal acolor as Color) as String ' 1, declaring the delegate class Private Mthedelegate as MyDelegate ' 2, defining the delegate variable Private Sub btnaddwindow_click (sender as Object, e as EventArgs) Handle  S Btnaddwindow.click Dim Achildform as New childform () Achildform.owner = Me Achildform.desktopbounds        = New Rectangle (* RND (), * RND (), + + * RND (), + + * RND ()) achildform.show () ' Create subform and display                              Dim newdelegate as MyDelegate = AddressOf Achildform.repaint ' 3, establishing a new delegate If Mthedelegate is Nothing Then        ' Multicast delegation is empty mthedelegate = newdelegate Sbstatus.text = ' Created first child form. '            Else mthedelegate = System.Delegate.Combine (mthedelegate, NewDelegate) ' 4, not empty, add ' show number of multicast delegate list ' Sbstatus.text = "Created child form" & Mthedelegate.getinvocationlist ().        Length & "." End If End Sub Private Sub BTNCOlor_click (sender as Object, e as EventArgs) Handles Btncolor.click If mthedelegate is Nothing Then MSGB Ox ("The Multicast delegate list is empty!") ") Exit Sub End If Dim dlgcolor as New ColorDialog () dlgcolor.showdialog () Mthedele Gate. Invoke (Dlgcolor.color) ' 6, multicast delegate execution, all brush color Sbstatus.text = "Updated" & Mthedelegate.getinvocationlist ().    Length & "Child form (s)." End Sub Public Sub childformclosing (ByVal achildform as ChildForm) Dim unneededdelegate as MyDelegate = Addresso        F Achildform.repaint mthedelegate = System.Delegate.Remove (mthedelegate, Unneededdelegate) ' 7, when closed, remove the delegate from this form        If mthedelegate is no then ' removed ' shows sbstatus.text = "Final child form has been closed." Else sbstatus.text = "child form closed," & Mthedelegate.getinvocationlist ().        Length & "form (s) remaining." End If End SubEnd Class
Description:Focus on the main form code to recognize the multicast delegate:
1 declares the delegate type (background brush color), 2 declares the multicast delegate variable, 3 adds the delegate according to the new subform, if NULL, is the first delegate, otherwise in 4 gradually adds the delegate matter. This forms a number of delegated matters. As long as one execution (i.e. 6 places) has been added to execute simultaneously (each subform changes the background individually), when a subform is closed, the subform class is called, the Childformclosing method in the main form is invoked, and the corresponding list is moved at 7.

VB.net study notes (23) re-knowledge entrusted

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.