C#Func<TResult> 委托
Func<TResult> 委托使用法
此委托类型最多有17重重载方法,最多可以带16个参数,最少可以带0个参数
以下是Func<TResult> 委托的常用方法
---------------------------------------------------------------常见委托使用方法---------------------------------------------------------------------------
using System; using System.IO; delegate bool WriteMethod(); public class TestDelegate { public static void Main() { OutputTarget output = new OutputTarget(); WriteMethod methodCall = output.SendToFile; if (methodCall()) Console.WriteLine("Success!"); else Console.WriteLine("File write operation failed."); } } 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; } } }
---------------------------------------------------------------Func<TResult>委托使用方法-------------------------------------------------------------
using System; using System.IO; public class TestDelegate { public static void Main() { OutputTarget output = new OutputTarget(); Func<bool> methodCall = output.SendToFile; if (methodCall()) Console.WriteLine("Success!"); else Console.WriteLine("File write operation failed."); } } 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; } } }
---------------------------------------------------------------Func<TResult>委托与匿名函数使用方法----------------------------------------------
using System; using System.IO; public class Anonymous { public static void Main() { OutputTarget output = new OutputTarget(); Func<bool> methodCall = delegate() { return output.SendToFile(); }; if (methodCall()) Console.WriteLine("Success!"); else Console.WriteLine("File write operation failed."); } } 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; } } }
---------------------------------------------------------------Func<TResult>委托与Lamda表达式使用方法------------------------------------------
using System; using System.IO; public class Anonymous { public static void Main() { OutputTarget output = new OutputTarget(); Func<bool> methodCall = () => output.SendToFile(); if (methodCall()) Console.WriteLine("Success!"); else Console.WriteLine("File write operation failed."); } } 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; } } }
重复就是力量,数量堆死质量

浙公网安备 33010602011771号