C#委託三——泛型委派

來源:互聯網
上載者:User

標籤: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#委託三——泛型委派

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.