Delegate, Lambda expression, and event series 07. Use EventHandler delegate, lambdaeventhandler

Source: Internet
Author: User

Delegate, Lambda expression, and event series 07. Use EventHandler delegate, lambdaeventhandler

When it comes to event registration, EventHandler is the most commonly used.


EventHandler is a delegate that receives two parameters. Sender refers to the initiator of an event and the etabulation event parameter.

 

□Use EventHandler for guessing games

 

EventHandler is used to implement a guessing game, one of which is made of scissors, stones, and cloth each time.

 

First, an observer is abstracted, which provides the event and the method for executing the event.

    public class FistGame
    {
        public string FistName { get; set; }
        public event EventHandler GuessFist;
        public void Start()
        {
            if (GuessFist != null)
            {
                GuessFist(this, EventArgs.Empty);
            }
        }
    }


Above, when the GuessFist event is called within the Start method, the real parameter this represents the FistGame class itself.

 

The client must have a method consistent with the EventHandler definition to register the EventHandler event of the FistGame class.

   class Program
    {
        static void Main(string[] args)
        {
FistGame jiandao = new FistGame () {FistName = "Scissors "};
            jiandao.GuessFist += GetFistResult;
FistGame shitou = new FistGame () {FistName = ""};
            shitou.GuessFist += GetFistResult;
FistGame bu = new FistGame () {FistName = "cloth "};
            bu.GuessFist += GetFistResult;
            FistGame finalFist = null;
            var temp = new Random().Next()%3;
            if (temp == 0)
            {
                finalFist = jiandao;
            }
            else if(temp == 1)
            {
                finalFist = shitou;
            }
            else
            {
                finalFist = bu;
            }
            finalFist.Start();
        }
        static void GetFistResult(object sender, EventArgs e)
        {
            FistGame fistGame = sender as FistGame;
Console. WriteLine ("the punch is:" + fistGame. FistName );
        }
    }


Above, the parameter list of the GetFistResult method conforms to the EventHandler definition and registers this method for the GuessFist event of each FistGame instance. Finally, the FistGame instance is determined based on the random number.

 

□Use EventHandler to pass event parameters

 

First, you need a class derived from EventArgs to inject an enumeration state through the constructor.

    public class FistGameEventArgs : EventArgs
    {
        public FistEnum CurrentFist { get; private set; }
        public FistGameEventArgs(FistEnum currentFist)
        {
            CurrentFist = currentFist;
        }
    }
    public enum FistEnum
    {
        jiandao,
        shitou,
        bu
    }

 

As the FistGame of the observer, EventHandler <TEventArgs> is now needed for implementation.

    public class FistGame
    {
        public string FistName { get; set; }
        public event EventHandler<FistGameEventArgs> GuessFist;
        public void Start()
        {
            if (GuessFist != null)
            {
                GuessFist(this, new FistGameEventArgs(FistEnum.jiandao));
            }
        }
    }

 

Client. The GetFistResult method consistent with the EventHandler Parameter List displays the event parameters.

        static void Main(string[] args)
        {
FistGame jiandao = new FistGame () {FistName = "Scissors "};
            jiandao.GuessFist += GetFistResult;
            jiandao.Start();
        }
        static void GetFistResult(object sender, FistGameEventArgs e)
        {
            FistGame fistGame = sender as FistGame;
Console. WriteLine ("obtained from the Name attribute, the punch of this output is:" + fistGame. FistName );
            switch (e.CurrentFist)
            {
                case FistEnum.jiandao:
Console. WriteLine ("obtained from the event parameter, this punch is: Scissors ");
                    break;
                case FistEnum.shitou:
Console. WriteLine ("obtained from the event parameter, this punch is: Stone ");
                    break;
                case FistEnum.bu:
Console. WriteLine ("obtained from the event parameter, this punch is: cloth ");
                    break;
            }
        }
    }    

 

Conclusion: Using the EventHandler delegate can not only implement event registration and cancellation, but also obtain the event initiator and event parameters.

 

 

"Delegation, Lambda expressions, and event series" include:

Delegate, Lambda expression, event series 01, Delegate, basic delegate usage, delegate Method and Target attribute delegate, Lambda expression, event series 02, when should I use delegate, Lambda expression, event series 03, from delegate to Lamda expression?

Delegation, Lambda expressions, event series 04, how the delegation chain is formed, multicast delegation, calling the delegation chain method, delegation chain Exception Handling delegation, Lambda expressions, event series 05, action delegate and closure delegate, Lambda expression, event series 06, use Action to implement observer mode, experience delegate and event difference delegate, Lambda expression, event series 07, use EventHandler delegate
Lambda expressions are not understood. Here is a simple example,

The biggest function is to use anonymous functions and linq queries.
This is used on the anonymous method:
Delegate int del (int I );
Del myDelegate = x => x * x;
Int j = myDelegate (5); // j = 25
Equivalent
Delegate int del (int I );
Del myDelegate = delegate (int I) {I = I * I ;};
Int j = myDelegate (5); // j = 25
As for the future of linq, do not go into details.

Direct I + 1 ???
Haha, you have not encountered some situations that must be delegated.
For example, for cross-thread calls, you can only use delegates, while lambda expressions are a very convenient way of writing. This is purely for convenience.

What is the Lambda expression? Can you give an example?

For example, for cross-thread calls, you can only use delegates, while lambda expressions are a very convenient way of writing. This is purely for convenience. C #3.0 sharp experience series (2): Lambda expressions (Level 300)
 

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.