C#事件发布与订阅

书店新书通知

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

namespace _1
{
    delegate void BookHand(string book);//引发事件
    class BookStore
    {
        public event BookHand OnNewBook;//定义事件
        public void NewBook(string book)//定义触发条件
        {
            OnNewBook(book);
        }
    }
    class Customer
    {
        private string _name;//顾客名

        public Customer(string name)//构造函数
        {
            _name = name;
        }

        void store_OnNewBook(string book)//输出语句,也是事件触发的结果函数
        {
            Console.WriteLine("{0}您好:书店新到新书《{1}》", _name, book);
        }

        public void Register(BookStore store)
        {
            store.OnNewBook += store_OnNewBook;//将结果函数并入事件中;
        }
    }
    //我认为的程序流程: 先有店和顾客,然后将顾客分到店中,也就是某个店的顾客(register),当书店进入新书执行(store.NewBook),这时候就会执行Customer的store_OnNewBook;
    class Program
    {
        static void Main(string[] args)
        {
            BookStore store=new BookStore();
            Customer c1=new Customer("小明");
            Customer c2=new Customer("赵丽");
            c1.Register(store);
            c2.Register(store);
            store.NewBook("c#程序设计");
        }
    }
}

你可能感兴趣的:(C#)