天天看點

說說委托代理func

Func<T, TResult> Delegate在3.5以上版本可用.

個人了解:不用再事先聲明一個delegate的類型了.可以直接用,也可以用lamba調用 .參數1:委托類型,參數二:傳回類型

Eg1;傳統型的.

using System;

delegatestring ConvertMethod(string inString);

publicclassDelegateExample

{

publicstaticvoid Main()

{

//Instantiate delegate to reference UppercaseString method

ConvertMethod convertMeth =UppercaseString;

string name = "Dakota";

//Use delegate instance to call UppercaseString method

Console.WriteLine(convertMeth(name));

}

privatestaticstring UppercaseString(string inputString)

return inputString.ToUpper();

}

//個人了解:1.代理在用的時候要執行個體化,

2.被調用的方法必須是static的。

3.代理的定義不能在public,private

4.傳回類型要相同(string),參數類型要相同。

Eg2: 用func

publicclassGenericFunc

Func<string, string> convertMethod =UppercaseString;

Console.WriteLine(convertMethod(name));

privatestaticstring UppercaseString(stringinputString)

//個人了解:相當于少了定義,其它和1相同。

2.用fund必須有傳回值,如果是沒有傳回值的,要用Action去替代。

Eg3:lamba

publicclassLambdaExpression

Func<string, string> convert = s=> s.ToUpper();

Console.WriteLine(convert(name));