C # The simplest example of Delegate: message transmission between two forms

Source: Internet
Author: User

Delegate [proxy and delegation] is a very important concept in C #. It can be deduced to the pointer of C ++, and can be extended to anonymous methods and lambda expressions. Now I will analyze the use of Delegate from a simple and practical example. Now there are two forms: Form1 and Form2. Two buttons: Button1 (Form) and Button2 (Form2 ). Code for Form1: private void button#click (object sender, EventArgs e) {Form2 frm = new Form2 (textBox1.Text); frm. setProperty + = new Form2.DelegateText (SetProperty2); frm. showDialog ();} private void SetProperty2 () {MessageBox. show ("OK");} Form2 code: public delegate void DelegateText (); public DelegateText SetProperty; private void button2_Click (object sender, EventArgs e) {www.2cto.com SetProperty ();} The analyzer has two short sections of code to see some benefits of Delegate. Before I wrote this function, I sent the form1 object to form2, click "form2" and call the public method of form1 on the from1 object of Tonggu. This code is awkward, that is, the so-called type is insecure and the method to be called must be disclosed, you also need to pass the form1 object to form2, which is obviously not the best solution. Now we can solve the Delegate problem, which is equivalent to the new form2 operation. In this way, I asked form2 to replace the attribute update operation, so that my method does not need to be exposed, form2 can only call this method, which achieves the so-called type security. Although this is a small example, it can gain a glimpse of the advantages of Some Delegate.

Related Article

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.