匿名方法的初步理解:
匿名方法允許我們定義委派物件可以接受的代碼塊。這個功能省去我們建立委託時想要傳遞給一個委託的小型代碼塊的一個額外的步驟。它也消除了類代碼中小型方法的混亂。讓我們看看:比方說,我們有一個字串集合命名為MyCollection。這個類有一個方法:獲得集合中滿足使用者提供的過濾準則的所有項,調用者決定在集合中的一個特殊項是否符合條件而被檢索到,作為從此方法返回數組的一部分。
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‘開頭的字元項數組 string[] AStrings = objMyCol.GetFilteredItemArray(FilterStringWithA); Console.WriteLine("----- Strings starting with letter ''A'' -----"); foreach(string s in AStrings) { Console.WriteLine(s); } //獲得集合中以字母’T‘開頭的字元項數組 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; } } |
可以看出對於每個我們想要提供的簡單過濾準則,我們應該定義一個方法(靜態或執行個體的)。這很快就搞亂了類的代碼。而用匿名方法,代碼變得相當自然。下面是這個Program類用匿名方法重寫後的:
public class Program { public delegate void MyDelegate(); 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‘開頭的字元項數組 string[] AStrings = objMyCol.GetFilteredItemArray(delegate(string sItem) { if (sItem[0] == ''A'') return true; else return false; }); Console.WriteLine("----- Strings starting with letter ''A'' -----"); foreach (string s in AStrings) { Console.WriteLine(s); } //獲得集合中以字母’ T ‘開頭的字元項數組 string[] TStrings = objMyCol.GetFilteredItemArray(delegate(string sItem) { if (sItem[0] == ''T'') return true; else return false; }); Console.WriteLine("----- Strings starting with letter ''T'' -----"); foreach (string s in TStrings) { Console.WriteLine(s); } } } |
正如上面樣本中的所示,我們已能用內聯代碼塊定義的過濾準則替代定義一個新的方法來代表每個過濾準則。老實說,用這種內聯代碼可能看起來自然並且避免了定義新方法,但是如果這個技術被用於更大的內聯代碼塊,這時代碼很快變得難於管理並可能導致代碼重複。因此,使用方法與內聯匿名方法都是委託/事件處理器的可選方案。