C#事件的概念及實例

下面給出一個如何理解C#中事件的概念:

以下代碼實現根據用戶在控制檯的輸入給定輸出

using System;
using System.Collections.Generic;
using System.Text;

namespace Event
{
    enum RequestType {AdRequest,PerasonMessageRequest };

    class UserRequestEventAgrs : EventArgs
    {
       private RequestType request;

        public UserRequestEventAgrs(RequestType requestType)
        : base()
        {
            this.request = requestType;
        }

        public RequestType Request
        {
            get
            {
                return this.request;
            }
        }
    }

    class UserInputMonitor
    {
        public delegate void UserRequest(object sender,UserRequestEventAgrs e);
        public event UserRequest OnUserRequest;
        public void Run()
        {
            while (true)
            {
         
                Console.WriteLine("A:Read advertisement please hit A then return");
                Console.WriteLine("P:Read person information please hit P then return");
                Console.WriteLine("E:Exit the appliction please hit E then return");
                Console.Write("Please select preferred option:");
                string ReadInput = Console.ReadLine();
                char UserInput=(ReadInput=="") ? ' ':char.ToUpper(ReadInput[0]);
                switch (UserInput)
             {
                    case 'A':
                        OnUserRequest(this, new UserRequestEventAgrs(RequestType.AdRequest));
                        break;
                    case 'P':
                        OnUserRequest(this, new UserRequestEventAgrs(RequestType.PerasonMessageRequest));
                        break;
                    case'E':
                        return;
                default:
                        break;
              }
            }
        }
    }

    class ManagerJnin
    {
        public ManagerJnin(UserInputMonitor monitor)
        {
            monitor.OnUserRequest +=new UserInputMonitor.UserRequest(UserRequestHandler);          
        }

        protected void UserRequestHandler(object sender, UserRequestEventAgrs e)
        {

            if (e.Request==RequestType.PerasonMessageRequest)
            {
                Console.WriteLine("/nYou select A and the result is:Xiaofan is a engineer!/n");
            }
            else if (e.Request==RequestType.AdRequest)
            {
                Console.WriteLine("/nYou select P and the result is:Xiaofan in the USTC/n");
            }
            else
            {
                Console.WriteLine("/nYou select exit the appliction!/n");
            }
        }

    }

    class Program
    {
        static void Main(string[] args)
        {
            UserInputMonitor inputMonitor = new UserInputMonitor();    
            ManagerJnin monitor = new ManagerJnin(inputMonitor);
            inputMonitor.Run();
        }
    }

  
}
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章