1. 程式人生 > >對委託與事件的深入理解

對委託與事件的深入理解

一、委託的理解

委託是一種型別(與列舉是一樣的):特殊的地方是它指向一個方法

 

二、委託的使用場景:將一個方法抽象出來作為引數傳遞

class Program
{
static void Main(string[] args)
{
//MyDelegate md = (s) => { Console.WriteLine(s); Console.ReadKey(); };//lamda expression
//md += Fun1;
//md("Hello Delegate!");

string[] strArry = { "aa","bb","cc"};
ArryProcess(strArry, (s) => { return s + "*"; });//傳入委託對陣列中的值進行處理
Console.ReadKey();
}

static void ArryProcess(string[] strArry,StrProcessDele dele)
{
for (int i = 0; i < strArry.Length; i++)
{
strArry[i] = dele(strArry[i]);
}
}

static void Fun1(string s)
{
Console.WriteLine(s+"1111");
Console.ReadKey();
}
}

delegate void MyDelegate (string str);

delegate string StrProcessDele(string str);

 

三、委託的特性

一個委託物件可以指向多個方法=》委託的組合

按順序執行註冊它的方法,一般只用於事件中。

 

四、事件的本質理解

實現對一件事情發生的監聽:(底層實現)

//宣告一個委託型別
delegate void OnCount10(int i);

class Program
{
static void Main(string[] args)
{
Count count = new Count();
count._onCount10 = onCount10;
count.Next();
Console.ReadKey();
}

//在得到整數10的時候就會執行這個函式---》呼叫的人並不知道是怎麼實現的,也不知道這個i是怎麼傳過來的
static void onCount10(int i)
{
Console.WriteLine("10的倍數:" + i);
}
}

class Count
{
public OnCount10 _onCount10;
private int i = 0;
public void Next()
{
while (true)
{
i++;
if (i % 10 == 0)
{
//到達10的整數的時候將這個數傳出去,通知事件
_onCount10(i);//具體呼叫的函式,設計Count類的人並不知道---->解耦的思想
}
}
}
}

注:利用+=的方式註冊多個委託響應函式