首页 > 代码库 > 事件与委托

事件与委托

//1.顾客去书店订购某种类型(计算机)的书,当书店新到某类型的书籍,会通知需要此类书的顾客。

//2.当顾客的需求类型发生变化时,需要通知书店。

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

namespace ConsoleApplication1
{

    public class Customer
    {
        public string name;
        public string type;

        public Customer(string m_name, string m_type)
        {
            name = m_name;
            type = m_type;
        }

        public void Register(BookStore store)
        {
          
            store.OnNewBook += new EventHandler(store_OnNewBook);
            BookStore.list.Add(this);

        }

        void store_OnNewBook(object sender, EventArgs e)
        {
            MyEventhandler temphandler = (MyEventhandler)e;

            if (temphandler.m_type == type)
            {
                Console.WriteLine("{0}:你好!,本店新近《{1}》", name, temphandler.m_name);
            }
        }

        public event EventHandler OnHandPro;

        public void HandPro()
        {
            MyEventhandler myhandler = new MyEventhandler(this.name, this.type);
            OnHandPro(this, myhandler);       
        }
    }

    public class MyEventhandler : EventArgs
    {
        public string m_name;
        public string m_type;

        public MyEventhandler(string name, string type)
        {
            m_name = name;
            m_type = type;
        }
    }
    public class BookStore
    {
        public static List<Customer> list = new List<Customer>();

        public event EventHandler OnNewBook;

        public void NewBook(string m_name, string m_type)
        {
            MyEventhandler myevethandler = new MyEventhandler(m_name, m_type);
            OnNewBook(this, myevethandler);
        }

        public void Register(Customer cs)
        {
            cs.OnHandPro += new EventHandler(cs_HandPro);
        }

        void cs_HandPro(object sender, EventArgs e)
        {
            Customer cs = (Customer)sender;

            foreach (Customer item in BookStore.list)
            {
                if (item.name == cs.name && item.type != cs.type)
                {
                    Console.WriteLine("书店你好!{0}需求的书籍类型更为{1}",cs.name, cs.type);
                    break;
                }
            }
          
        }
    }

 

    class Program
    {
        static void Main()
        {
            BookStore store = new BookStore();           
            Customer cs1 = new Customer("TOm", "计算机");
            Customer cs2 = new Customer("Jim", "英语");
            cs1.Register(store);
            cs2.Register(store);
            store.NewBook("数据结构", "计算机");
            store.NewBook("英语2", "英语");
            cs1 = new Customer("TOm", "计算机2");
            store.Register(cs1);
            store.Register(cs2);
            cs1.HandPro();
            cs2.HandPro();
            Console.ReadLine();
        }

    }
}

事件与委托