C# 2.0中采用了匿名方法,它容许咱们能以一种直观的方式理解委托。匿名方法容许咱们直接对一个委托对象定义代码段。当咱们建立一个仅有小段代码的委托的时候,匿名方法提供了更为灵活的解决之路。让咱们来看看下面这段代码:spa
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>(); }
咱们再写出以下的代码来引用上面的类:code
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"); // get an array of string items in the collection that start // with letter 'A' // string[] AStrings = objMyCol.GetFilteredItemArray(FilterStringWithA); Console.WriteLine("----- Strings starting with letter 'A' -----"); foreach(string s in AStrings) { Console.WriteLine(s); } // get an array of string items in the collection that start // with letter '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; } }
若是采用匿名方法,代码将变得更加天然。下面是采用匿名方法修改事后的代码:对象
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"); // get an array of string items in the collection that start // with letter '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); } // get an array of string items in the collection that start // with letter '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); } } }
匿名方法老是从一个delegate关键字,后面跟着参数内使用的方法和方法体自己。从上面的代码示例中,用户不须要指定的匿名方法的返回类型,它是根据在方法体内部的返回状态来推断出来的。 .NET CLR并不能执行自由的匿名代码段, CLR要求它执行的是每个方法的类型应该是一个静态方法或实例方法。因此,当你在类中写匿名方法而且编译代码,C#编译器在后台针对这些匿名方法来建立静态或实例方法。所以,匿名方法只是一个方便的语法来定义本身的类内部的方法传递给委托(表明处理程序/事件处理程序)。事件
当你编译了上面这个例子后,C#编译器对这两个匿名方法建立了两个私有静态方法,而后用这些静态方法的地址来替代了匿名方法。以下图 所示,而编译器建立静态方法或者实例方法,这取决于匿名方法内部的代码段。get