程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> 委托事件,c#委托事件

委托事件,c#委托事件

編輯:C#入門知識

委托事件,c#委托事件


class PubEventArgs : EventArgs
    {
        private readonly string _magname;

        public string Magname
        {
            get { return _magname; }
        } 

        public PubEventArgs(string magname)
        {
            _magname = magname;
        }
    }
    class Event//創建事件類
    {
        public delegate void PubComputerEventHandle(object sender,PubEventArgs e);//聲明委托
        public event PubComputerEventHandle PubComputer;//創建委托鏈,即事件
        public delegate void PubLifeEventHandle(object sender, PubEventArgs e);
        public event PubLifeEventHandle PubLife;
        public virtual void OnComputer(PubEventArgs e)
        {
            PubComputerEventHandle handle = PubComputer;
            if (handle != null)
            {
                handle(this,e);
            }
        }
        public virtual void OnLife(PubEventArgs e)
        {
            PubLifeEventHandle handle = PubLife;
            if (handle != null)
            {
                handle(this, e);
            }
        }
        public void IsComputer(string magname)//創建觸發事件過程
        {
            Console.WriteLine("發行"+magname+"雜志");
            OnComputer(new PubEventArgs(magname));
        }
        public void IsLife(string magname)
        {
            Console.WriteLine("發行" + magname + "雜志");
            OnComputer(new PubEventArgs(magname));
        }
    }
    class Man//創建操作主體
    {
        public string name;
        public Man(string name)
        {
            this.name = name;
        }
        public void Order(object sender, PubEventArgs e)//在主體中創建被委托的函數
        {
            Console.WriteLine(name + "訂閱" + e.Magname + "刊物");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Event e = new Event();//事件建好
            Man zs = new Man("張三");//主體建好
            e.PubComputer += new Event.PubComputerEventHandle(zs.Order);//調用主體的被委托函數
            Man ls = new Man("李四");
            e.PubComputer += new Event.PubComputerEventHandle(ls.Order);
            e.PubLife += new Event.PubLifeEventHandle(ls.Order);
            e.IsComputer("電腦");//觸發事件
            e.IsLife("生活");
            Console.Read();
        }
    }

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved