C # Delegate (1)

Source: Internet
Author: User

The notes are from the entrusting part of Jin xuliang's Electronic Teaching Plan "Commission and event" and his book ". NET4.0 Object-Oriented Programming basics"
Delegation is the technical basis for events, asynchronous calls, and multi-thread development in. NET.
A delegate can be seen as a method container (the most typical is the + = and-= symbols in the control event). After loading a specific method, it can be called as a method.

C # How the compiler handles delegation:

public delegate int MathOptDelegate(int val1,int val2);

The preceding delegate is compiled by the compiler as follows:

public class MathOptDelegate:System.MulticastDelegate
{
    public MathOptDelegate(Object target,Int32 methodPtr);
    public void virtual Invoke(Int32 val1,Int32 val2);
    public virtual IAsyncResult BeginInvoke(
        Int32 val1,Int32 val2,ASyncCallback,Object object);
    public virtual void EndInvoke(IAsyncResult result);
}

MulticastDelegate indicates multi-channel broadcast delegation. There is a constructor with parameters of Object and Int32, and three virtual methods.

A simple delegation example:

        public class MathOpt
        {
            public int Add(int arg1,int arg2)
            {
                return arg1+arg2;
            }
        }
        
        public delegate int MathOptDelegate(int val1,int val2);
        void MainFormLoad(object sender, EventArgs e)
        {
            MathOptDelegate oppDel;
            MathOpt obj=new MathOpt();
            oppDel=obj.Add;
            string str=oppDel(20,12).ToString();
            MessageBox.Show(string.Format("20+12={0}",str),"Delegate Demo", MessageBoxButtons.OK);
        }

Define a delegate whose signature type is int func (int val1, int val2). Define a function Add (int, int) according to the delegate signature)

Then, instantiate a delegate, that is, oppDel, assign the method that complies with the delegate signature to the delegate, and call this method by instantiating the delegate. The call method is oppDel (int, int ), the format is only related to the delegate signature, and has nothing to do with the specific method name.

Each delegate determines the signature of a method. In most cases, methods with different signatures cannot be assigned to the same delegate variable.

The following is an example of a four-Rule operation using delegation:

Define a delegate:

public delegate double CalculateDelegate(double x,double y);


This delegate determines which operation is used during the operation. The complete code is as follows:
    public delegate double CalculateDelegate(double x,double y);
        private CalculateDelegate curOpt;
        void DoCalculate(CalculateDelegate calMethod)
        {
            double x,y;
            x=int.Parse(textBox1.Text);y=int.Parse(textBox2.Text);
LabResult. Text = string. Format ("Result: {0}", calMethod (x, y ));
        }
        double Add(double x,double y){return x+y;}
        double Subtract(double x,double y){return x-y;}
        double Multiplicate(double x,double y){return x*y;}
        double Divide(double x,double y){return x/y;}
        void RadioButton1CheckedChanged(object sender, EventArgs e)
        {
            foreach(RadioButton r in groupBox2.Controls)
            {
                if(r is RadioButton)
                {
                    if(r.Checked==true)
                    {
                        int i=groupBox2.Controls.IndexOf(r);
                        switch(i)
                        {
                            case 0:
                                curOpt=Add;
                                break;
                            case 1:
                                curOpt=Subtract;
                                break;
                            case 2:
                                curOpt=Multiplicate;
                                break;
                            case 3:
                                curOpt=Divide;
                                break;
                        }
                    }
                }
            }
            DoCalculate(curOpt);
        }

After the delegate variable is defined, a call method is defined. The call method uses the delegate as the parameter. When the Check attribute of RadioButton changes, the delegate variable also changes. After the delegate variable is assigned a value, call the trigger method. Is simply changing the Commission

Example of multi-form communication using delegation:

To facilitate the assignment of delegate variables, place the delegate variables in the form. The specific code is as follows:

In Program. cs:

public delegate void ShowInfoDelegate(string info);

In the main form:

        void MainFormLoad(object sender,EventArgs e)
        {
            ChildForm c=new ChildForm();
            c.recorder=Record;
            c.Show();
        }
        
        private void Record(string str)
        {
            label1.Text=str;
        }

Code from the form:

        public ShowInfoDelegate recorder;
        private int counter;
        void Button1Click(object sender, EventArgs e)
        {
            counter++;
            if(recorder!=null)
                recorder(counter.ToString());
        }

When loading a sub-form, assign a display record method in the main form to the delegate variable from the form, and then trigger it by the Button in the form.

At the tip of the iceberg, there are generic delegation, anonymous methods, Lambda expressions, and Callbacks. They are only in this book. There is also a section "in-depth exploration of delegate technology insider ", because the technology and understanding capabilities are not at home, we will not absorb them first.

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.