.NET (一)委託第一講:什麼是委託

來源:互聯網
上載者:User

標籤:個數   object   lambda   log   main   代碼   耦合   定義   一行代碼   

1.為什麼要使用委託?

生活中的委託就是委託他人幫我們去辦一件事情,程式中的委託類似。看下面的例子

    class Class1    {        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);            //過濾偶數            Even(list);            ObjectDumper.Write(list);        }        //過濾集合中的偶數        public static void Even(List<int> list)        {            for (int i = 0; i < list.Count; i++)            {                if (list[i] % 2 != 0)                {                    list.RemoveAt(i);                    i--;                }            }        }        //過濾集合中的奇數        public static void Odd(List<int> list)        {            for (int i = 0; i < list.Count; i++)            {                if (list[i] % 2 == 0)                {                    list.RemoveAt(i);                    i--;                }            }        }    }

通過上面的例子我們發現 Even()方法 和 Odd()方法只有一行代碼不同,使用委託可以將方法當成參數傳遞,這樣做的好處是使程式之間的耦合降低,同時節省代碼。

改造上面的代碼如下:

   class Class2    {        //聲明委託        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);            //過濾偶數            Cal cal = new Cal(Even);            MyCal(list, cal);            ObjectDumper.Write(list);        }               public static bool Even(int num)        {            if (num % 2 == 0)            {                return true;            }            return false;        }        public static bool Odd(int num)        {            if (num % 2 != 0)            {                return true;            }            return false;        }        public static void MyCal(List<int> list,Cal cal)        {            for (int i = 0; i < list.Count; i++)            {                if (cal(list[i]))                {                    list.RemoveAt(i);                    i--;                }            }        }    }

委託描述的是方法的簽名(包括參數類型、個數、傳回值),上面聲明一個委託 Cal ,和 我們要調用的方法一樣,接收一個 int類型的參數,返回bool類型。

public delegate bool Cal(int num);

使用New關鍵字建立委託:

Cal cal = new Cal(Even);

最後調用cal,得到所有偶數項的集合

MyCal(list, cal);

我們在 MyCal(List<int> list,Cal cal) 方法中,傳遞了一個委託 作為參數,Cal描述的是 Even 或者Odd方法的簽名,這樣可以在調用的時候決定 是過濾奇數 還是 過濾偶數。

這和我們直接調用Even或Odd方法有什麼不同,不是更麻煩了嗎,接著往下看:

我們可以將過濾的方法改成如下代碼:

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

正因為MyCal方法接收的是一個委託,所以我們可以在不定義Even或Odd的時候,使用匿名委託。

這樣省去了不必要的代碼,使結構看起來更簡單,也不需要預先定義好方法,在調用的時候我們臨時決定。

.NET 還給我們提供了更進一步的簡化,使用Lambda運算式:

//代碼演化//lamadaMyCal(list, (i) => { return i % 2 == 0 ? true : false; });

i表示輸入參數 (i) => { return i % 2 == 0 ? true : false; } 是一條lambda語句,標識過濾偶數。

完整的代碼如下:

//聲明委託        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);            MyCal(list, (i) => { return i % 2 == 0 ? true : false; });            ObjectDumper.Write(list);        }        public static void MyCal(List<int> list, Cal cal)        {            for (int i = 0; i < list.Count; i++)            {                if (cal(list[i]))                {                    list.RemoveAt(i);                    i--;                }            }        }

這樣做是不是比開始的時候簡單多了,無論後面再怎麼添加新的過濾方式,我們只需要修改我們的lambda語句,其他的都不需要變動,這就是委託的魅力。

.NET (一)委託第一講:什麼是委託

聯繫我們

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