C#匿名方法学习总结

开发 后端
这里介绍C#匿名方法学习总结,C#匿名方法允许我们定义委托对象可以接受的代码块。这个功能省去我们创建委托时想要传递给一个委托的小型代码块的一个额外的步骤。

匿名方法是C#2.0的一个新的语言特性。本文的主要内容是提供给读者关于C#匿名方法的内部实现和工作方式的一个更好的理解。本文无意于成为C#匿名方法的完全语言特性参考。

C#匿名方法允许我们定义委托对象可以接受的代码块。这个功能省去我们创建委托时想要传递给一个委托的小型代码块的一个额外的步骤。它也消除了类代码中小型方法的混乱。让我们看看:比方说,我们有一个字符串集合命名为MyCollection。这个类有一个方法:获得集合中满足用户提供的过滤准则的所有项,调用者决定在集合中的一个特殊项是否符合条件而被检索到,作为从此方法返回数组的一部分。

  1. public class MyCollection  
  2. {  
  3. public delegate bool SelectItem(string sItem);  
  4. public string[] GetFilteredItemArray(SelectItem itemFilter)  
  5. {  
  6. List<string> sList = new List<string>();  
  7. foreach(string sItem in m_sList)  
  8. {  
  9. if (itemFilter(sItem) == true) sList.Add(sItem);  
  10. }  
  11. return sList.ToArray();  
  12. }  
  13.  
  14. public List<string> ItemList  
  15. {  
  16. get  
  17. {  
  18. return m_sList;  
  19. }  
  20. }  
  21. private List<string> m_sList = new List<string>();  

我们可以用上面定义的类写如下所示的代码:

  1. public class Program  
  2. {  
  3. public static void Main(string[] args)  
  4. {  
  5. MyCollection objMyCol = new MyCollection();  
  6. objMyCol.ItemList.Add("Aditya");  
  7. objMyCol.ItemList.Add("Tanu");  
  8. objMyCol.ItemList.Add("Manoj");  
  9. objMyCol.ItemList.Add("Ahan");  
  10. objMyCol.ItemList.Add("Hasi");  
  11.  
  12. //获得集合中以字母’A‘开头的字符项数组  
  13. string[] AStrings = objMyCol.GetFilteredItemArray(FilterStringWithA);  
  14. Console.WriteLine("----- Strings starting with letter ''A'' -----");  
  15. foreach(string s in AStrings)  
  16. {  
  17. Console.WriteLine(s);  
  18. }  
  19. //获得集合中以字母’T‘开头的字符项数组  
  20. string[] TStrings = objMyCol.GetFilteredItemArray(FilterStringWithT);  
  21. Console.WriteLine("----- Strings starting with letter ''T'' -----");  
  22. foreach(string s in TStrings)  
  23. {  
  24. Console.WriteLine(s);  
  25. }  
  26. }  
  27.  
  28. public static bool FilterStringWithA(string sItem)  
  29. {  
  30. if (sItem[0] == ''A'')  
  31. return true;  
  32. else  
  33. return false;  
  34. }  
  35. public static bool FilterStringWithT(string sItem)  
  36. {  
  37. if (sItem[0] == ''T'')  
  38. return true;  
  39. else  
  40. return false;  
  41. }  

以上介绍C#匿名方法学习总结

【编辑推荐】

  1. 如何用C#和ADO.NET访问
  2. 浅析C# Switch语句
  3. C#验证输入方法详解
  4. 简单介绍C# 匿名方法
  5. C# FileSystemWatcher对象
责任编辑:佚名 来源: 天极网
相关推荐

2009-08-12 17:32:44

C#反射方法

2009-08-31 16:51:11

C# Main()方法

2009-08-27 09:27:49

C#扩展方法

2009-08-14 17:38:08

C#改写方法

2009-08-20 16:15:19

C# 匿名方法

2009-08-20 16:28:45

C#匿名方法

2009-08-20 16:25:59

C# 匿名方法

2009-08-27 17:51:34

C#匿名方法

2009-08-14 09:41:03

C#遗传算法

2009-08-27 17:47:18

C#匿名方法作为参数传

2009-08-10 17:25:58

C#匿名类型

2009-08-13 18:21:52

C#学习笔记

2009-08-26 15:46:01

C#匿名类型

2009-07-31 14:08:54

C# 匿名函数

2009-08-13 18:13:27

C#学习经验

2009-09-09 13:31:15

C# TextBox

2009-08-20 18:06:18

学习C#接口

2009-08-27 10:19:22

C#匿名类型

2009-09-01 10:58:46

C#匿名类型对象

2009-08-11 14:20:41

C# .NET学习经验
点赞
收藏

51CTO技术栈公众号