namespace ConsoleTest2008
{
    public delegate void TestEvent(int myX);
    class AT {
        public AT()
        {
            _x = 100;
            _y = 200;
        }
        //解構式測試
        ~AT() {
            Console.WriteLine("AT is Die");
        }
        private int _x;
        private int _y;
        public event TestEvent isLarge;
      
        public int Attr {
            get {
                return _x;
            }
            set
            {
                if (value < 0)
                {
                    _x = 0;
                }
                else
                {
                    if (value > 5)
                    {
                        isLarge(value);
                    }
                    _x = value;
                }
            }
        }
    }
    class Program
    {
      
        static void Main(string[] args)
        {
            AT at = new AT();
            Console.WriteLine("事件測試");
            at.isLarge+=new TestEvent(at_isLarge);
            at.Attr = 9;
            GC.Collect();
            /* Ctrl+F5 編譯時不會程式自動結束*/
        }
        static void at_isLarge(int _x)
        {
            Console.WriteLine("X:{0}太大", _x);
        }
    }
C#事件指派幾個要點
宣告委託型態
delegate void TestEvent(int myX);透過delegate 宣告事件處裡函式的基本型態
之後的事件指派函式必須長的委託者長的一樣
宣告事件
public event TestEvent isLarge;透過event宣告事件名稱跟委託者型態
上面程式代表事件 isLarge必須給樣式為TestEvent的人處裡
制於事件何時發生必須透過物件程式自己判斷
         if (value > 5)
          {
                        isLarge(value);
          }
    如上 ,當value大於5時 event就會被觸發
事件可以當函數直接呼叫,但是參數要傳對
事件委託
上面宣告好之後就開始正式委託
            at.isLarge+=new TestEvent(at_isLarge);
            at.Attr = 9;
   物件at將isLarge事件委託給at_isLarge處裡
C#事件的委託很像C++函數指標,就是把函數當成變數來使用
可以把delegate看成一種宣告函數指標
可以用於很多方面
delegate bool Compare(int a,int b);
.......
bool isSmall(int a,int b){...}
bool isBig(int a,int b){...}
Compare cmp=new Compare(isSmall);//將cmp指向函式isSmall
swap(cmp);
cmp==new Compare(isBig);//將cmp指向函式isBig
swap(cmp);
....
void swap(Compare cmp){...}
藉此可達成另一種多型的應用
 
沒有留言:
張貼留言