建一個控制台應用程式。
定義一個委托
delegate int AddDel(int a,int b);
定義靜态方法:
static int AddStaticFunc(int a, int b)
{
return a + b;
}
調用:
AddDel del = new AddDel(AddStaticFunc);
int result = del(3, 4);
Console.WriteLine(result);
定義一個執行個體方法:
public int AddInstanceFunc(int a, int b)
{
return a + b+1;
}
Program p = new Program();
del += p.AddInstanceFunc;
輸出8 說明:
多點傳播委托的時候:拿到委托傳回值的、是最後一個委托的方法的執行結果
多點傳播委托的内部如何實作呢?(分析)
委托的内部組要有三個部分組成:
1._methodPtr方法指針(指向目前委托指向的方法記憶體位址)
2._target目标對象(對象下面的方法)靜态方法的時候為null
3.委托鍊(委托數組)---+=就代表就在次執行上面的方法-----就形成了委托數組
泛型委托
兩個傳入參數一個傳回值(必須與類型對應)
Func<int, int, int> funcDemo = new Func<int, int, int>(AddStaticFunc);
靜态的方法:
static int AddStaticFunc(int a, int b)
{
return a + b;
}
調用:
int result = funcDemo(3, 4);
匿名方法的簡化:
Func<int, int, int> funcDemo = delegate(int a, int b) { return a + b; };
Lambda語句:
Func<int, int, int> funcDemo = (int a, int b) => { return a + b; };
Lbmbda表達式:
Func<int, int, int> funcDemo = (int a, int b) => a + b;
前面有限制,自動推斷:
Func<int, int, int> funcDemo = (a,b) => a + b;
還有一個泛型委托Action:(沒有傳回值)
為什麼要定義兩個泛型委托?一個有傳回值,一個沒有傳回值(這樣就不用認為的定義)
應用:
List<string> strList = new List<string>() {
"3","9","32","7"
};
要求:把集合中 字元串小于“6”的列印出來
var temp=strList.Where(delegate(string a) { return a.CompareTo("6") < 6; });
where 方法内部:周遊strList集合,把每個元素傳到委托裡面執行,如果委托傳回true那麼把元素選擇出來,最後把所有滿足條件的元素一塊傳回
foreach (var item in temp)
{
Console.WriteLine(item);
}
用自定義的擴充方法:
擴充方法三要素:1.靜态類 2.靜态方法 3.this關鍵字
public static List<T> MyWhere<T>(this List<T> list,Func<T,bool> funcWhere)
{
List<T> result = new List<T>();
foreach (var item in list)
{
if( funcWhere(item))
{
result.Add(item);
}
}
return result;
}
用自己的擴充方法:
var temp =strList.MyWhere(delegate(string a) { return a.CompareTo("6") < 0; });
Lambda方式:
方法類型的限制 可以省略。但是如果你是顯示的限制,必須滿足限制
var temp = strList.MyWhere(a => a.CompareTo("6") < 0);