.NET (二)委託第二講:內建委託Func

來源:互聯網
上載者:User

標籤:out   each   參數   修改   for   類型   調用   style   new   

在上一章節中,我們自己聲明了一個委託:

 public delegate bool Cal(int num);

接受int參數,返回bool類型,目的是過濾集合中的 奇數 或者 偶數。

.NET 為我們內建了一個泛型委派,用於處理這種情況,省去了自訂的麻煩。

public delegate TResult Func<in T, out TResult>(T arg);

Func是.NET定義的委託,接受任何參數,並返回自訂類型結果。

我們可以將代碼修改為:public static void MyCal(List<int> list, Cal cal)

public static void MyCal(List<int> list, Func<int,bool> func)        {            for (int i = 0; i < list.Count; i++)            {                if (func(list[i]))                {                    list.RemoveAt(i);                    i--;                }            }        }

將原本方法中的參數Cal 修改為 Func類型。同時刪除public delegate bool Cal(int num);委託聲明語句。

像如下調用:

static void Main(String[] args)        {            List<int> list = new List<int>();            list.Add(1);            list.Add(2);            list.Add(3);            list.Add(4);            list.Add(5);            list.Add(7);            list.Add(6);            Func<int, bool> func = new Func<int, bool>(Even);            MyCal(list, func);                        foreach (int i in list)            {                Console.WriteLine(i);            }        }

我們仍然可以省略委託名,使用匿名委託,修改代碼為:

            MyCal(list, delegate(int i)            {                if (i % 2 == 0)                {                    return true;                }                return false;            });

.NET (二)委託第二講:內建委託Func

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.