如上所示,在TestClass的Test方法中,action委托调用了同在TestClass类中的私有方法Print,并对Test方法中的局部变量index进行了读写。在加上C# 3.0中Lambda表达式的新特性,匿名方法的使用得到了极大的推广。不过,如果使用不当,匿名方法也容易造成难以发现的问题。
问题案例
某位兄弟最近在一个简单的数据导入程序,主要工作是从文本文件中读取数据,进行分析和重组,然后写入数据库。其逻辑大致如下:
- static void Process() {
- List<Item> batchItems = new List<Item>(); foreach (var item in ...)
- { batchItems.Add(item);
- if (batchItems.Count > 1000) {
- DataContext db = new DataContext(); db.Items.InsertAllOnSubmit(batchItems);
- db.SubmitChanges(); batchItems = new List<Item>();
- } }
- }










