C# 筆記 Func 委托、Action 委托


https://blog.csdn.net/wanglui1990/article/details/79303894

Func<ΤResult> 委托:代理(delegate)一個返回類型為「由參數指定的類型的值(TResul)」 的無參方法。使用 Func<ΤResult> 委托,無需顯式定義一個委托與方法的關聯。 
Func<ΤResult>原型:

public delegate TResult Func<out TResult>()
  • 1

Func<ΤResult>示例: 
主方法

namespace 異步操作 {  class Program { static void Main(string[] args) { FuncDelegate fDel = new FuncDelegate(); fDel.ExplicitlyDeclaresTest(); fDel.SimplifiesByFuncT(); fDel.SimplifiesByFuncTAndAnonymousMethod(); fDel.SimplifiesByFuncTAndLambda(); fDel.ExtendFuncT(); ActionTtest aDel = new ActionTtest(); aDel.ExplicitlyDeclaresActionTTest(); aDel.SimplifiesByActionT(); aDel.SimplifiesByActionTAndAnonymousMethod(); aDel.SimplifiesByActionTAndLambda(); aDel.ExtendActionT(); Console.Read(); } } }

示例代碼:

namespace 異步操作
{
    //Func<TResult>() 委托:返回類型為TResult的無參方法。 //Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult> 委托:返回TResult類型,帶9個參數的方法。 //當您使用 Func<TResult> 委托時,您無需顯式定義一個委托,用於封裝無參數的方法。 例如,下面的代碼顯式聲明的委托名為 WriteMethod 和分配的引用 OutputTarget.SendToFile 實例到其委托實例的方法。 //https://msdn.microsoft.com/zh-cn/library/bb534960(v=vs.110).aspx public class OutputTarget { public bool SendToFile() { try { string fn = Path.GetTempFileName(); StreamWriter sw = new StreamWriter(fn); sw.WriteLine("Hello, World!"); sw.Close(); return true; } catch { return false; } } } delegate bool WriteMethod(); class FuncDelegate { //顯式聲明委托與方法的關聯 public void ExplicitlyDeclaresTest() { OutputTarget output = new OutputTarget(); WriteMethod methodCall = output.SendToFile;//建立委托與方法的關聯。 if (methodCall())//執行此行時,跳轉去執行綁定的方法SendToFile() Console.WriteLine("Success!"); else Console.WriteLine("File write operation failed."); } //使用Func<TResult>簡化 委托與方法的關聯 public void SimplifiesByFuncT() { OutputTarget output = new OutputTarget(); Func<bool> methodCall = output.SendToFile;//簡化關聯 if (methodCall())//執行此行時,跳轉去執行綁定的方法SendToFile() Console.WriteLine("Success!"); else Console.WriteLine("File write operation failed."); } //使用Func<TResult>和匿名方法簡化 委托與方法的關聯 public void SimplifiesByFuncTAndAnonymousMethod() { OutputTarget output = new OutputTarget(); Func<bool> methodCall = delegate () { return output.SendToFile(); };//匿名方法簡化Func<T>與方法的關聯 if (methodCall())//執行此行時,跳轉去執行 綁定的匿名方法() { return output.SendToFile(); },執行完后返回 Console.WriteLine("Success!"); else Console.WriteLine("File write operation failed."); } //使用Func<TResult>和Lambda、匿名方法簡化 委托與方法的關聯 public void SimplifiesByFuncTAndLambda() { OutputTarget output = new OutputTarget(); Func<bool> methodCall = () => output.SendToFile();//Lambda、匿名方法 簡化Func<T>與方法的關聯 if (methodCall()) // 執行此行時,跳轉去執行 綁定的() => output.SendToFile(),執行完后返回 Console.WriteLine("Success!"); else Console.WriteLine("File write operation failed."); } //擴展:以Funct<T>未參數類型傳遞。 public void ExtendFuncT() { //():匿名無參方法。() =>方法名,指派匿名無參方法去執行另外一個方法。 LazyValue<int> lazyOne = new LazyValue<int>(() => ExpensiveOne());//匿名無參方法被指派去執行ExpensiveOne LazyValue<long> lazyTwo = new LazyValue<long>(() => ExpensiveTwo("apple"));//匿名無參方法被指派去執行ExpensiveTwo Console.WriteLine("LazyValue objects have been created."); //泛型類別根據 關聯的委托與方法 取值。 Console.WriteLine(lazyOne.Value);//跳轉到() => ExpensiveOne(),執行LazyValue<T>.Value的取值,然后顯示結果。 Console.WriteLine(lazyTwo.Value);//跳轉到() => ExpensiveTwo("apple"),執行LazyValue<T>.Value的取值,然后顯示結果。 } //無參測試方法 static int ExpensiveOne() { Console.WriteLine("\nExpensiveOne() is executing."); return 1; } //計算字串長度 static long ExpensiveTwo(string input) { Console.WriteLine("\nExpensiveTwo() is executing."); return (long)input.Length; } } //擴展:自定義泛型類別LazyValue T,以Funct<T>為參數類型傳遞。 class LazyValue<T> where T : struct { private T? val;//或 Nullable<T> val; //標記返回類型T,同時用於保存Func<T>委托的方法的返回值 private Func<T> getValue; //返回類型為T的委托 // 構造。參數Funct<T>類型:傳入的參數為返回類型為TResult(任何類型)的無參方法。 public LazyValue(Func<T> func) { val = null; getValue = func; } public T Value { get { if (val == null) val = getValue();//取得委托方法的返回值。 return (T)val; //強制抓換委托方法返回值類型。 } } } }

Action<Τ> 委托:代理(delegate)無返回值 參數類型為 T 的無參方法。使用 Action<Τ> 委托,無需顯式定義一個委托與方法的關聯。 
Action<Τ>原型:

public delegate void Action<in T>( T obj )

 

 

Action<Τ>示例代碼:

namespace 異步操作
{

    delegate void DisplayMessage(string message);//委托:一個string類型參數、無返回值的方法 public class ActionTOutputTarget { public void ShowWindowsMessage(string message) { Console.WriteLine(message); } } class ActionTtest { //顯式聲明委托與方法的關聯 public void ExplicitlyDeclaresActionTTest() { DisplayMessage methodCall;//委托名methodCall ActionTOutputTarget output = new ActionTOutputTarget(); if (Environment.GetCommandLineArgs().Length > 1)//接收命令行輸入 methodCall = output.ShowWindowsMessage; else methodCall = Console.WriteLine; methodCall("Hello, World!"); //執行帶參方法。 } //使用Action<T>簡化 委托與方法的關聯 public void SimplifiesByActionT() { ActionTOutputTarget output = new ActionTOutputTarget(); Action<string> methodCall = output.ShowWindowsMessage;//簡化關聯。關聯帶一個string類型參數的方法 if (Environment.GetCommandLineArgs().Length > 1)//接收命令行輸入 methodCall = output.ShowWindowsMessage; else methodCall = Console.WriteLine; methodCall("Hello, World!"); //執行帶參方法。 } //使用Action<T>和匿名方法簡化 委托與方法的關聯 public void SimplifiesByActionTAndAnonymousMethod() { ActionTOutputTarget output = new ActionTOutputTarget(); Action<string> methodCall = output.ShowWindowsMessage;//簡化關聯。關聯帶一個string類型參數的方法 if (Environment.GetCommandLineArgs().Length > 1)//接收命令行輸入 methodCall = delegate (string s) { output.ShowWindowsMessage(s); };//匿名方法參數簽名(string s) else methodCall = delegate (string s) { Console.WriteLine(s); }; methodCall("Hello, World!"); //執行帶參方法。 } //使用Action<T>和Lambda、匿名方法簡化 委托與方法的關聯 public void SimplifiesByActionTAndLambda() { ActionTOutputTarget output = new ActionTOutputTarget(); Action<string> methodCall = output.ShowWindowsMessage;//簡化關聯。關聯帶一個string類型參數的方法 if (Environment.GetCommandLineArgs().Length > 1)//接收命令行輸入 methodCall = (string s)=> { output.ShowWindowsMessage(s); };//Lambda參數s傳遞給匿名方法,方法體{ output.ShowWindowsMessage(s); } else methodCall = (string s)=> { Console.WriteLine(s); }; methodCall("Hello, World!"); //執行帶參方法。 } //擴展:以Action<T>為參數類型傳遞。 public void ExtendActionT() { List<String> names = new List<String>(); names.Add("Bruce"); names.Add("Alfred"); names.Add("Tim"); names.Add("Richard"); Console.WriteLine("==========List<string>.ForEach(Action<T> action>======="); //以Action<T>類型為參數 List<string> ForEach:public void ForEach(Action<T> action); names.ForEach(Print); Console.WriteLine("==========匿名方法 delegate(string name)={Console.WriteLine();}======="); // 匿名方法 names.ForEach(delegate (string name) { Console.WriteLine("console:"+name); }); } private void Print(string s) { Console.WriteLine("Print:"+s); } } }

 

總結:以后如果要新建委托與方法關聯,可簡化代碼如下(使用匿名方法+Lambda+Func<Τ>)。

//Func<bool> methodCall = () => output.SendToFile() //methodCall()//執行 關聯的方法() Func<關聯方法返回類型> methodCall = () => 關聯的方法()//傳遞匿名無參方法() 並與想要執行方法關聯(=>),可關聯方法可任意參數,但必須有返回類型(無返回值的用Action<T>)。 methodCall()。//執行 關聯的方法


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM