導致類別程式碼膨脹、難以維護。
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);
}
}
深入探討匿名方法內部實作機制(閉包、捕獲變數、編譯器產生的巢狀類別),確保正確使用避免不可預期結果。