標籤:action func 泛型委派
PanPen120在CSDN上原創,如其他網站轉載請注意排版和寫明出處:
研究委託,因為有函數指標的基礎,還容易上手,但是對於一些概念和實踐,總是為了弄的非常清楚而糾結,這幾篇關於委託的文章我是結合《C#與.NET4進階程式設計》、MSDN、借鑒其他人的博文來總結話語,以最直接簡潔的話來闡述清楚
關鍵字:
Func Action delegate三種
一般說的泛型就是Func和Action,是委託的簡寫
我將delegate這個正版的委託也加入是因為他也可以寫成泛型
描述:
固定委託的參數個數,但參數的類型是動態可變
目的\優勢:
省去了定義委託類型的步驟
Action與Fun區別:
Action無傳回值,Action重載的參數個數有1-4個
Func有傳回值。Func重載的參數個數有1-4個
Action樣本:
namespace testAction{ class Program { // public delegate void Action<T>(T arg); //注釋的這一行是Action的原型,這句可寫可不寫,即上面提到的目的... //注釋的這一行是Action的原型,由此可看出Action無傳回值 static void Main(string[] args) { Action<int> action = PrintfMyAge; action(4); Action<string> action2 = PrintfMyName; action2("PanPen120"); Console.ReadLine(); } static void PrintfMyAge(int myAge) { Console.WriteLine("My Age is {0}",myAge); } static void PrintfMyName(string myName) { Console.WriteLine("My Name is {0}",myName); } }}
Func樣本:
//區別是委託註冊的函數都是有傳回值的namespace testAction{ class Program { static void Main(string[] args) { Func<int,int> action = PrintfMyAge; action(4); Func<string, int> action2 = PrintfMyName; action2("PanPen120"); Console.ReadLine(); } static int PrintfMyAge(int myAge) { Console.WriteLine("My Age is {0}", myAge); return 1; } static int PrintfMyName(string myName) { Console.WriteLine("My Name is {0}", myName); return 1; } }}
delegate樣本:
namespace GenericDelegate{ public delegate void MyGenericDelegate<T>(T arg); class Program { static void Main(string[] args) { MyGenericDelegate<string> strTarget = new MyGenericDelegate<string>(StringTarget); StringTarget("Some string data"); MyGenericDelegate<int> intTarget = new MyGenericDelegate<int>(IntTarget); intTarget(9); Console.ReadLine(); } static void StringTarget(string arg) { Console.WriteLine("arg in uppercase is : {0}", arg.ToUpper()); } static void IntTarget(int arg) { Console.WriteLine("++arg is : {0}", ++arg); } }}
備忘:
如果用到泛型委派,就用Action或者Func,沒必要有簡單的不用還要用delegate這種方式
C#委託三——泛型委派