C#Func<TResult> 委託
阿新 • • 發佈:2020-11-27
Func<TResult> 委託使用法
此委託型別最多有17重過載方法,最多可以帶16個引數,最少可以帶0個引數
以下是Func<TResult> 委託的常用方法
---------------------------------------------------------------常見委託使用方法---------------------------------------------------------------------------
using System; using System.IO; delegate bool WriteMethod();View Codepublic 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; } } }View Code
---------------------------------------------------------------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; } } }View Code
---------------------------------------------------------------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; } } }View Code