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
using System;
publicclassGenericFunc
{
publicstaticvoid Main()
{
//Instantiate delegate to reference UppercaseString method
Func<string, string> convertMethod =UppercaseString;
string name = "Dakota";
//Use delegate instance to call UppercaseString method
Console.WriteLine(convertMethod(name));
}
privatestaticstring UppercaseString(stringinputString)
{
return inputString.ToUpper();
}
}
//個人理解:相當於少了定義,其它和1相同。
2.用fund必須有返回值,如果是沒有返回值的,要用Action去替代。
Eg3:lamba
using System;
publicclassLambdaExpression
{
publicstaticvoid Main()
{
Func<string, string> convert = s=> s.ToUpper();
string name = "Dakota";
Console.WriteLine(convert(name));
}
}
//個人理解:相當於把方法的實現放在func中。