Implementing communication between forms using delegates in. Net

Source: Internet
Author: User
Tags end net static class visibility
For simple communication between forms, Using the VB6.0 method can meet our requirements, but in some complex architectural applications, this approach is a bit stretched, and there is one drawback to this approach, which is that it works only with forms that are added through the. NET Form Wizard, and that we cannot add to the Forms object collection for custom form types. and other methods, such as constructor parameters, and so on, in the form of a large number of reference to each other members, resulting in a great coupling between each other, very detrimental to the independence of form modules, which does not conform to the idea of good software design patterns.

If we want to access a custom member of another form in a form, the visibility of the member must be set to public or be exposed through attributes, but if the visibility is set to public, this will inevitably undermine the principle of type encapsulation, And that's the way we are. NET development is quite happy to do, especially for initial contact. NET developers, the first thing to think of when accessing a member of another type is to set the visibility of the member to public, which is certainly not a mistake, but it is clearly inappropriate to take this approach as your primary inspiration, at least from an object-oriented perspective.

Under. NET, we also provide another powerful mechanism for implementing form communication, which is the delegate. A delegate can be understood as a type-safe function pointer. NET, the implementation of the event is based on the delegate. I am not going to go into the details of the delegation in this article, and there will be an article devoted to this concept. Here I demonstrate this method by adding item items to a ListBox control in another form in a form. So you need two forms, a mainfrm form, a childfrm form, and a middle class as a bridge between MainFrm and Childfrm. I will also give you vb.net and C # Two languages so that you can make comparisons.

First, the MainFrm form, in the MainFrm form, drag a ListBox control, and the Mainfrm.vb code is as follows (for simplicity, this eliminates automatically generated code):

Public Class FORM3

Private Sub form3_load (ByVal sender as System.Object, ByVal e as System.EventArgs) Handles MyBase.Load
AddHandler Middle.sendmessage, AddressOf Domethod
End Sub

Private Sub Domethod (ByVal getstr as String)
ME.LISTBOX1.ITEMS.ADD (GETSTR)
End Sub
End Class
Look at the Childfrm form, drag a TextBox and a button control, and press the button button to add an item to the ListBox control in the MainFrm form after you enter a value in the TextBox.

Public Class Form2

Private Sub Button1_click_1 (ByVal sender as System.Object, ByVal e as System.EventArgs) Handles Button1.Click
Middle.dosendmessage (TextBox1.Text)
TextBox1.Text = ""
Textbox1.focus ()
End Sub
End Class
Finally look at the middle class:

Public Class Middle
Public Shared Event SendMessage (ByVal str as String)
Public Shared Sub dosendmessage (ByVal str as String)
RaiseEvent SendMessage (str)
End Sub

End Class
To better demonstrate the independence between MAINFRM and childfrm, modify the Application.Designer.vb code:

<global.system.diagnostics.debuggerstepthroughattribute () >

Protected Overrides Sub Oncreatemainform ()
Me.mainform = Global.WindowsApplication3.MainFrm
Childfrm.show ()
End Sub
Okay, the code's over, isn't it easy? As can be seen from the above code, through the middle class, mainfrm and Childfrm, and the middle class, they are no longer referencing each other's internal members, in addition to the coupling of the parameters, and thus become more independent.

The following is the corresponding C # code, MainFrm.cs:

public partial class Mainfrm:form
{
private void MainFrm _load (object sender, EventArgs e)
{
Middle.sendevent + = new Middle.sendmessage (this. Domethod);
}
public void Domethod (string getstr)
{
LISTBOX1.ITEMS.ADD (GETSTR);
}
}

ChildFrm.cs:

public partial class Childfrm:form
{
Public Childfrm ()
{
InitializeComponent ();
}

private void Button1_Click (object sender, EventArgs e)
{
Middle.dosendmessage (This.textBox1.Text);
TextBox1.Text = "";
Textbox1.focus ();
}
}

Middle.cs:

public static class middle
{
public delegate void SendMessage (String str);
public static event SendMessage Sendevent;
public static void Dosendmessage (String str)
{
Sendevent (str);
}
}
Again, let's revise the Program.cs code:

Static Class Program
{
[STAThread]
static void Main ()
{
Application.enablevisualstyles ();
Application.setcompatibletextrenderingdefault (FALSE);
Application.Run (New Form1 ());
Form1 mainfrm = new Form1 ();
Childfrm secondfrm = new Childfrm ();
Secondfrm.show ();
Application.Run (MAINFRM);
}
}
Comparing the above vb.net and C # code, we can see that vb.net allows you to declare events directly with the event keyword, and C # must be the first to declare the event's delegate prototype, and then to declare the event based on that delegate. From this point of view vb.net appears more concise, in fact, vb.net compiler in the back will automatically define a delegate object for us, and the C # code declaration of the delegate generated IL code is the same, this can be viewed by the ILDasm Intermediate Code Viewer. Raises an event, VB. NET is through the RaiseEvent keyword plus event name, and C # is by using the event name directly, finally is the code that binds the event, VB. NET is through the AddHandler keyword, C # through the overloaded + = operator, for the above two points, the compiler will also generate a consistent IL code for us.

Of course, the above example is relatively simple, but we can fully delegate the implementation of complex forms of communication, such as the delivery of complex data types, at the same time, can be in the design of better structure of the intermediate communication class. But we should also remind you not to use the Commission, it will increase the complexity of the program, should be based on their own needs to consider how to use.

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.