浅析C#的事件处理和自定义事件

一、简单的自定义事件(1):无参数

namespace UserInputMonitor

{

    class UserInputMonitor

    {

        public delegate void UserRequest(object sender, EventArgs e);

        //定义委托

        public event UserRequest OnUserRequest;

        //此委托类型类型的事件

        public void Run()

        {

            bool finished = false;

            do

            {

                if (Console.ReadLine() == "h")

                {

                    OnUserRequest(this, new EventArgs());

                }

                else if (Console.ReadLine() == "e")

                {

                    finished = true;

                }

            } while (!finished);

        }

    }

    public class Client

    {

        public static void Main()

        {

            UserInputMonitor monitor = new UserInputMonitor();

            new Client(monitor);

            monitor.Run();

        }

        private void ShowMessage(object sender, EventArgs e)

        {

            Console.WriteLine("HaHa!!");

        }

        Client(UserInputMonitor m)

        {

            m.OnUserRequest += new UserInputMonitor.UserRequest(this.ShowMessage);

            //m.OnUserRequest+=new m.UserRequest(this.ShowMessage);

            //注意这种写法是错误的,因为委托是静态的

        }

    }

}

二、简单的自定义事件(2):包含参数

class MyEventArgs:EventArgs

{

    private string keyChars;

   

    public MyEventArgs(string keyChars)

    {

        this.keyChars = keyChars;

    }

   

    public string KeyChars

    {

        get

        {

            return keyChars;

        }

    }

}

class UserInputMonitor

{

    //定义委托

    public delegate void UserRequest(object sender,MyEventArgs e);

    //此委托类型类型的事件,用户累加客户端事件

    public event UserRequest OnUserRequest;

    public void Run() //定义此事件激发的条件

    {

        bool finished=false;

        do

        {

           string inputString= Console.ReadLine();

           if (inputString != "")

               OnUserRequest(this, new MyEventArgs(inputString));

           else

               finished = true;

        }while(!finished);

     }

}

public class Client

{

     public static void Main()

     {

          UserInputMonitor monitor=new UserInputMonitor();

          new Client(monitor);

          monitor.Run();

     }

     private void ShowMessage(object sender,MyEventArgs e)

     {

          Console.WriteLine("捕捉到:{0}",e.KeyChars);

     }

     Client(UserInputMonitor m)

     {

          m.OnUserRequest+=new UserInputMonitor.UserRequest(this.ShowMessage);

          //m.OnUserRequest+=new m.UserRequest(this.ShowMessage);

          //注意这种写法是错误的,因为委托是静态的

     }

}

原文地址:https://www.cnblogs.com/qqhfeng/p/1674102.html