C#匿名方法學(xué)習(xí)總結(jié)
匿名方法是C#2.0的一個(gè)新的語(yǔ)言特性。本文的主要內(nèi)容是提供給讀者關(guān)于C#匿名方法的內(nèi)部實(shí)現(xiàn)和工作方式的一個(gè)更好的理解。本文無(wú)意于成為C#匿名方法的完全語(yǔ)言特性參考。
C#匿名方法允許我們定義委托對(duì)象可以接受的代碼塊。這個(gè)功能省去我們創(chuàng)建委托時(shí)想要傳遞給一個(gè)委托的小型代碼塊的一個(gè)額外的步驟。它也消除了類代碼中小型方法的混亂。讓我們看看:比方說(shuō),我們有一個(gè)字符串集合命名為MyCollection。這個(gè)類有一個(gè)方法:獲得集合中滿足用戶提供的過(guò)濾準(zhǔn)則的所有項(xiàng),調(diào)用者決定在集合中的一個(gè)特殊項(xiàng)是否符合條件而被檢索到,作為從此方法返回?cái)?shù)組的一部分。
- public class MyCollection
- {
- public delegate bool SelectItem(string sItem);
- public string[] GetFilteredItemArray(SelectItem itemFilter)
- {
- List<string> sList = new List<string>();
- foreach(string sItem in m_sList)
- {
- if (itemFilter(sItem) == true) sList.Add(sItem);
- }
- return sList.ToArray();
- }
- public List<string> ItemList
- {
- get
- {
- return m_sList;
- }
- }
- private List<string> m_sList = new List<string>();
- }
我們可以用上面定義的類寫如下所示的代碼:
- public class Program
- {
- public static void Main(string[] args)
- {
- MyCollection objMyCol = new MyCollection();
- objMyCol.ItemList.Add("Aditya");
- objMyCol.ItemList.Add("Tanu");
- objMyCol.ItemList.Add("Manoj");
- objMyCol.ItemList.Add("Ahan");
- objMyCol.ItemList.Add("Hasi");
- //獲得集合中以字母’A‘開頭的字符項(xiàng)數(shù)組
- string[] AStrings = objMyCol.GetFilteredItemArray(FilterStringWithA);
- Console.WriteLine("----- Strings starting with letter ''A'' -----");
- foreach(string s in AStrings)
- {
- Console.WriteLine(s);
- }
- //獲得集合中以字母’T‘開頭的字符項(xiàng)數(shù)組
- string[] TStrings = objMyCol.GetFilteredItemArray(FilterStringWithT);
- Console.WriteLine("----- Strings starting with letter ''T'' -----");
- foreach(string s in TStrings)
- {
- Console.WriteLine(s);
- }
- }
- public static bool FilterStringWithA(string sItem)
- {
- if (sItem[0] == ''A'')
- return true;
- else
- return false;
- }
- public static bool FilterStringWithT(string sItem)
- {
- if (sItem[0] == ''T'')
- return true;
- else
- return false;
- }
- }
以上介紹C#匿名方法學(xué)習(xí)總結(jié)
【編輯推薦】