C# 委託與事件

來源:互聯網
上載者:User

標籤:動作   null   blog   rgs   test   自動完成   str   函數   對象   

c#事件 委託:

    1.類似觀察者模式。
    2.當某個對象(類),執行某個動作時,之前委託的事情會自動完成。
    (如B,C訂閱A的事件,當A執行某動作,B和C均會按照約定進行對應動作)



使用步驟:

    1.定義 delegate委託類,event 事件
        
        //首領A:舉杯委託
    public delegate void RaiseEventHandler(string hand);
        public class A
        {
        
        // 首領A:舉杯事件      
        public event RaiseEventHandler RaiseEvent;
    
      
    2.綁定事件對應的函數
        // 舉杯
        public void Raise(string hand)
        {
            Console.WriteLine("首領A{0}手舉杯", hand);
            // 調用舉杯事件,傳入左或右手作為參數
            if (RaiseEvent!=null)
            {
                RaiseEvent(hand);
            }
        }


    

    


    3.編寫約定


     public class B
        {
            A a;

            public B(A a){
            this.a = a;
            a.RaiseEvent += new RaiseEventHandler(a_RaiseEvent); // 訂閱舉杯事件
              
                    }
         
        // 首領舉杯時的動作     
        void a_RaiseEvent(string hand)
        {
            if (hand.Equals("左"))
            {
                Attack();
            }
        }
      
        // 約定的攻擊函數   
        public void Attack()
        {
            Console.WriteLine("部下B發起攻擊,大喊:猛人張飛來也!");
        }
    }



    4.測試

    class Test{
        static void Main(string[] args){
            A a = new A(); // 定義首領A
 
            // 首領A左手舉杯
            a.Raise("左");

            // 首領A右手舉杯
            //a.Raise("右");
 
         
            // 由於B和C訂閱了A的事件,所以無需任何代碼,B和C均會按照約定進行動作。
                }
        }

 

 

原文:http://www.cnblogs.com/yinqixin/p/5056307.html

C# 委託與事件

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.