To entrust

Read a lot about trust, knowledge 1. Before the event, but has not been used on their own (short contact time, and the project is not only to develop and debug) for some relaxed time ago, to sum up the knowledge of the two main reference heroes

    Blog: http: //www.tracefact.net/tech/009.html; https: //www.cnblogs.com/yinqixin/p/5056307.html

    These two bloggers directly to cite examples, say the benefits of using delegates, this can be avoided if else swich other statements too complex and mixed on the envelope and post prone to problems.

2. commission

    Commissioned from the data structure that is a class, so that user-defined types from the perspective of design patterns provided commissioned abstract methods. A delegate is an abstract method, it is stored in a series with the same signature and return back to the type of method

    the address of. When invoked delegate, delegate all methods included will be executed.

     Proxy statement:

   (1) to deleagate begin with a keyword.

   (2) the return type of the delegate type + name + parameter list.

     

 public/ private delegate void MyDel(int x);

 

      Declare a delegate variable:

      MyDel del1, del2; // variable declarations, and other types of agreement.

      Initialization delegate variable:

    (1) consisting of a number of the new operator as follows:

                   Delegate type name; a set of parentheses, which contains a method invocation as the first member of the list of names. Examples of a method or process may be a static method.  

del1 = new MyDel( myInstObj.MyM1 );
del2 = new MyDel( SClass.OtherM2 );

 

    (2) use the shortcut syntax

                 Syntax quick key, it is only by the process configuration specifier. Thus able, because between the method name and its corresponding implicit conversion delegate types.

del1 = myInstObj.MyM1;
del2 = SClass.OtherM2;

      Delegate invocation:

            Delegate invocation with a method call similar. After the delegate invocation, each method invocation list will be executed.    

            Before calling the commission should determine whether the commission is empty . Call empty delegate throws an exception.

 

IF ( null =! del) 
{ 
     del (); // delegate call 
}

 

       Anonymous method:        

          Inline anonymous method is a method declared a delegate at initialization.

          basic structure:

Deleage (parameter) {} block of statements

         E.g:

 
 
delegate int MyDel (int x); // define a delegate 

MyDel del = delegate (int x) {return x;};

         We can see from the above, the anonymous method is not displayed declare the return value .

      Lambda expressions:

       Lambda expressions are mainly used to simplify the syntax of anonymous methods. In the anonymous method, delegate keyword bit redundant, because the compiler already know that we will assign to the delegate methods. By a few simple steps, we can convert anonymous method to Lambda expressions:

  • Delete the delegate keyword
  • Anti Lambda operator => between the parameter list and anonymous method body. Lambda operator read as "goes to".
MyDel del = delegate (int x) {return x;}; // anonymous method 
MyDel del2 = (int x) = > {return x;}; // Lambda expressions 
MyDel del3 = x => {return x}; / / shorthand Lambda expressions

 3. Introduction fog people blog

     

This article does not introduce any concept, designed to help students quickly spend delegates and events into a higher realm of C #.

  • First of all, we need to know, in the end have to use delegates and events under what circumstances it?

Consider the following scenario: A leader engage a Banquet, B and C each commanded men led impacted on both sides of the screen, as stipulated by the glass so that: If the left toast, then B led blaze; hand if toast , the blaze led C; if the direct fall cup, B and C at the same time the blaze. Specific methods B and C attack, A leader does not care. (Complete code in the final text.)

Students have brains react quickly, immediately said, this logic, judgment statement with an IF condition not to get it:

Copy the code
1 if (left toast) 
 2 { 
 . 3 B led blaze;   
 . 4} 
 . 5 the else IF (right toast) 
 . 6 { 
 . 7 C led blaze;   
 . 8} 
 . 9 the else IF (direct throw cup) 
10 { 
. 11 with B team blaze; 
12 is led popped C;   
13 is} 
14 the else 
15 { 
16 anything   
17}
Copy the code

If really so simple, that I write this article doing it. Ask the students to seriously think about: A leader would send a signal when it? He estimated that even he himself did not know. So this pseudo-code above, where are you going to insert it? Is B and C have been kept doing it with the judgment While loop? It is clearly inappropriate. More importantly, if extended look, men more than B and C, but B, C, D, E, and so on, each person has their own different ways to respond to the call of the leadership, then the leader in terms of A, respectively, to talk each men deal with the pseudo-code, will be endless expansion and improvement, it is clearly not what we want.

Correct logic should be, anything else B and C, regardless of the occurrence of the feast, just waiting for the leader issued a toast or fall signal Cup, once the leader signals A, equivalent to inform all men, good men all agreed, are flew their actions!

We define three classes, and each analog A leader men B, C:

Copy the code
    /// <summary>
    /// 首领A
    /// </summary>
    public class A
    { 
    
    }
    /// <summary>
    /// 部下B
    /// </summary>
    public class B
    { 
    
    }
    /// <summary>
    /// 部下C
    /// </summary>
    public class C
    { 
    
    }
Copy the code

A leader class has two methods toast and wrestling cup, wherein the method toast with a parameter for delivering a toast left, or right toast. Men of B and C, each of which has an attack method.

Copy the code
    /// <Summary> 
    /// Boss A 
    /// </ Summary> 
    public class A 
    { 
        /// <Summary> 
        /// toast 
        /// </ Summary> 
        /// <param name = "Hand" > hand: left, right </ param> 
        public void the Raise (String hand) 
        { 
            Console.WriteLine ( "Boss hand toast A {0}", hand); 
        } 
        /// <Summary> 
        /// throw Cup 
        @ / </ Summary> 
        public void Fall () 
        { 
            Console.WriteLine ( "A leader cup wrestling"); 
        } 
    } 
    /// <Summary> 
    /// men B 
    /// </ Summary>
    public class B
    {
        /// <Summary> 
        /// attack 
        /// </ Summary> 
        public void Attack () 
        { 
            Console.WriteLine ( "B men attack"); 
        } 
    } 
    /// <Summary> 
    /// men C 
    // / </ Summary> 
    public class C 
    { 
        /// <Summary> 
        /// attack 
        /// </ Summary> 
        public void attack () 
        { 
            Console.WriteLine ( "C men attack"); 
        } 
    }
Copy the code

So far, three separate classes, construction is completed. So, how men let B and C, before going to the appropriate action based on the code word leader do?
A leader we need in class, using a method, the intent to pass out. Before the leader class A, are defined with a parameter of the delegate RaiseEventHandler toast and throw a cup with no parameter delegate FallEventHandler. Naming convention is to add EventHandler, do not ask me to deliver them in the name of the method why, the article describes why so high, you can go to inspection. The purpose of this paper is that the church you how to quickly use delegates and events. Of course, you can not follow this naming convention, has no effect on the operation of the program, but will increase the difficulty of themselves or others in the future to read the code.

delegate void RaiseEventHandler(string hand);
delegate void FallEventHandler();

Then, the leader of A class, define two events. After you drag and drop like this in a WinForm Button, double-click the Button, you can edit the event.

Copy the code
        /// <Summary> 
        /// A toast event leader 
        /// </ Summary> 
        public Event RaiseEventHandler the RaiseEvent; 
        /// <Summary> 
        /// A leader cup drop event 
        /// </ Summary> 
        public Event FallEventHandler FallEvent;
Copy the code

Well, done after the above two steps, you can throw the cup in a toast and chief method A, call the above two events. Thus, if B and C subscribe to that event, it can be automatically executed.

Copy the code
        /// <Summary> 
        /// toast 
        /// </ Summary> 
        /// <param name = "Hand"> Hand: left, right </ param> 
        public void the Raise (String Hand) 
        { 
            Console.WriteLine ( "A {0} hand leader toast", hand); 
            // call event toast, passed as a parameter to the right or left 
            IF (the RaiseEvent = null)! 
            { 
                the RaiseEvent (hand); 
            } 
        } 
        /// <Summary> 
        / // throw Cup 
        /// </ the Summary> 
        public void Fall () 
        { 
            Console.WriteLine ( "A leader fell Cup"); 
            // call throw Cup event 
            if (FallEvent!= null) =null)
            {
                Fall Wait ();
            }
        }
Copy the code

Also, do not ask why write. According to the above-described operation. Once cooked this way, understand the meaning, naturally understand why so wrote.

In the hearts of men B and C, there must be the leader of A, A hint to perform it. Therefore, class B and class C, declare one of A, the statement may be instantiated by B and C of the constructor. After instantiation, you can subscribe to the class B and class C, class A in the event.

The complete code is as follows:

Copy the code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace raiseFail
{
    class Program
    {
        static void Main(string[] args)
        {
            A master = new A();
            B buxia = new B(master);
            C buxia1 = new C(master);
            master.Raise("Left");
            master.Fall();
            master.Raise("Right");
            master.Fall();
            Console.ReadKey();
        }
    }
    /// <Summary>
    /// A toast leader
    /// </ Summary>
    /// <param name = "Hand"> left right </ param>
    public void RaiseEventHandler the delegate (String Hand);
    /// < Summary>
    /// A cup drop operation
    /// </ Summary>
    public void FallEventHandler the delegate ();
    /// <Summary>
    ///
    /// </ Summary>
    public class A
    {
        public Event RaiseEventHandler the RaiseEvent;
        public Event FallEvent FallEventHandler;
        public void the Raise (String Hand)    // equivalent to clicking the button to trigger the event         {             Console.WriteLine ( " A {0} hand leader toast ", hand);


            if(RaiseEvent != null)
            {
                RaiseEvent(hand);
            }
        }
        public void Fall()
        {
            Console.WriteLine("首领A摔杯");
            if (FallEvent != null)
            {
                FallEvent();
            }
        }
    }
    /// <Summary>
    /// men B
    /// </ Summary>
    public class B
    {
        A A;
        public B (A A)
        {
            this.a = A;
            a.RaiseEvent + = new new RaiseEventHandler (a_RaiseHand); / / Subscribe button is equivalent to toast the event registration event (binding method name)
            a.FallEvent + = new new FallEventHandler (a_FallEvent); // subscribe to fall Cup event
        }
        public void a_RaiseHand (Hand String)
        {
            IF (hand.Equals ( "Left "))
            {
                Attack ();
            }
        }
        public void a_FallEvent ()
        {
            Attack ();
        }
        Private void Attack ()
        {
            Console.WriteLine ( "B men attack, shouting: Meng Fei people to be");
        }
    }
    /// <Summary>
    /// men C
    /// </ Summary>
    public class C
    {
     A A;
    public C (A A)
    {
             this.a = A;
             a.RaiseEvent + = new new RaiseEventHandler (a_RaiseHand); / / subscribe event toast
             a.FallEvent + = new FallEventHandler (a_FallEvent) ; // throw cup event subscription
     }
    void a_RaiseHand public (String Hand)
        {
            IF (hand.Equals ( "Right"))
            {
                Attack ();
            }
        }
    public void a_FallEvent ()
        {
            Attack ();
        }
    Private void Attack ()
        {
            Console.WriteLine ( "men C attack, crossover hit a fallen tiger ~ ");
        }
    }
}

 4. Zhang Ziyang blog

 

  

Guess you like

Origin www.cnblogs.com/xingyuanzier/p/12193285.html