.NET Framework委托的预定义方法介绍

开发 后端
我们将会在这篇文章中为大家详细介绍有关.NET Framework委托的一些预定义方法,希望能够对又需要的朋友有所帮助。

.NET Framework开发环境对于开发人员来说是一个非常实用的开发平台。我们可以通过它来进行WEB应用程序的部署。前言:从.NET Framework2.0开始以来,系统预定义的委托使使代码看起来有点像“天书”,再加上匿名表达式,以及后面Lambda表达式的“掺和”,代码就更加难懂了,于是自己就一点点查MSDN,到现在终于有点入门了。#t#

用.NET Framework委托:

  1. 1、public delegate void Action< T>(T obj )   
  2. 2、public delegate TResult Func< TResult>()  
  3. 3、public delegate bool Predicate< T>(T obj)  

其中:Action和Func还包括从不带任何参数到最多四个参数的重载?

1、public delegate void Action< T>(T obj )

封装一个方法,该方法只采用一个参数并且不返回值。

Code

  1. Action< string> messageTarget;   
  2. messageTarget = s => Console.
    WriteLine(s);  
  3. messageTarget("Hello, World!"); 

2、public delegate TResult Func<TResult>()

封装一个具有一个参数并返回 TResult 参数指定的类型值的方法。

类型参数T

此委托封装的方法的参数类型。

TResult

此.NET Framework委托封装的方法的返回值类型

Code
 

  1. public static void Main()  
  2. {  
  3. // Instantiate delegate to reference UppercaseString method  
  4. ConvertMethod convertMeth = UppercaseString;  
  5. string name = "Dakota";  
  6. // Use delegate instance to call UppercaseString method  
  7. Console.WriteLine(convertMeth(name));  
  8. }  
  9. private static string UppercaseString(string inputString)  
  10. {  
  11. return inputString.ToUpper();  

 

3、public delegate bool Predicate<T>(T obj)

表示定义一组条件并确定指定对象是否符合这些条件的方法。

类型参数

T:要比较的对象的类型。

返回值

如果 obj 符合由此委托表示的方法中定义的条件,则为 true;否则为 false。

Code

  1. public static void Main()  
  2. {  
  3. // Create an array of five Point 
    structures.  
  4. Point[] points = { new Point(100, 200),   
  5. new Point(150, 250), new Point(250, 375),   
  6. new Point(275, 395), new Point(295, 450) };  
  7. Point first = Array.Find(points, ProductGT10);  
  8. // Display the first structure found.  
  9. Console.WriteLine("Found: X = {0}, 
    Y = {1}", first.X, first.Y);  
  10. }  
  11. // This method implements the test 
    condition for the Find  
  12. // method.  
  13. private static bool ProductGT10(Point p)  
  14. {  
  15. if (p.X * p.Y > 100000)  
  16. {  
  17. return true;  
  18. }  
  19. else  
  20. {  
  21. return false;  
  22. }  

 

责任编辑:曹凯 来源: 博客园
相关推荐

2010-01-05 18:49:57

.NET Framew

2009-08-18 11:08:24

.Net Framew

2012-05-04 15:54:16

ASP.NET

2009-07-20 16:12:21

ASP.NET Fra

2009-12-15 11:28:34

.NET Framew

2010-01-05 09:57:34

.NET Framew

2009-09-11 12:00:33

C#预定义数据类型

2010-01-06 17:12:26

.Net Framew

2010-01-05 17:39:10

.NET Framew

2009-07-20 16:04:37

ASP.NET fra

2010-01-05 16:20:46

.NET Framew

2010-01-15 15:26:46

VB.NET自定义类型

2010-01-05 10:17:35

.NET Framew

2010-01-06 18:33:56

.Net Framew

2009-05-26 09:09:50

.NET FramewStream.Read基础类

2010-01-06 11:30:22

.NET Framew

2010-01-06 16:40:11

.Net Framew

2010-01-06 10:07:35

.NET Framew

2010-01-05 15:35:21

.NET Framew

2010-01-05 15:43:13

.NET Framew
点赞
收藏

51CTO技术栈公众号