A13_委託與事件的區別

/*
 * 
 * 事件不能聲明局部實例
 * 事件不能作爲方法的參數
 * 
 * 
 * ***/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace A13_DifferentBetweenDelegateAndEvent
{
    class Demo1
    {

        public Action actHandler;       //委託
        public event Action eveEvent;   //事件

        public Demo1()
        {
            //委託註冊
            actHandler += TestMethod1;
            actHandler += TestMethod2;
            //事件註冊
            eveEvent += TestMethod1;
            eveEvent += TestMethod2;
        }

        public void TestMethod1()
        {
            Console.WriteLine("TestMethod1");
        }

        public void TestMethod2()
        {
            Console.WriteLine("TestMethod2");
        }

        public void Test1()
        {
            if (actHandler!=null)
            {
                actHandler();
            }
            if (eveEvent != null)
            {
                eveEvent();
            }
        }

  

        public void Test2()
        {
            //定義委託的局部實例
            Action actHandler2 = TestMethod1;
            actHandler2 += TestMethod2;
        }

        static void Main(string[] args)
        {
            Demo1 obj = new Demo1();
            obj.Test1();
        }
    }
}











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