关于C#委托你不可不知的几件事

开发 后端
我们今天要给大家讲讲C#委托,虽然这属于基础知识,但弄清楚了委托究竟是怎么一回事还是有助于大家更好的开发。

委托是C#中非常重要的一个概念,并在C#中得到了丰富的应用,如事件,线程等。那什么是委托呢?具体来说,委托是一种引用方法的类型。一旦为委托分配了方法,委托将与该方法具有完全相同的行为。委托方法的使用可以像其他任何方法一样,具有参数和返回值。

委托具有以下特点:

委托类似于 C++ 函数指针,但它是类型安全的。

委托允许将方法作为参数进行传递。

委托可用于定义回调方法。

委托可以链接在一起;例如,可以对一个事件调用多个方法。

方法不需要与委托签名精确匹配。有关更多信息,请参见协变和逆变。

C# 2.0 版引入了匿名方法的概念,此类方法允许将代码块作为参数传递,以代替单独定义的方法。

在C#中使用委托分为三步:

1.定义委托:

  1. //声明委托  
  2. public delegate void MyDel(); 

2.实例化委托:

  1. TestDel t = new TestDel();   
  2. Console.WriteLine("-----以下是简单使用委托演示--------");  
  3. //t.MyMethod();  
  4.  
  5. ///实例化委托,用一个方法来进行实例化  
  6. ///该方法签名要与委托签名一致  
  7. MyDel del = new MyDel(t.MyMethod); 

3.调用委托:

  1. ///调用委托  
  2. del(); 

好了,其实委托的变化很复杂,但基本都会符合这么三个步骤,说过了,这些,再来看一下完整的代码

  1. namespace DelegateDemo{    
  2.   //声明委托      
  3. public delegate void MyDel();      
  4. //声明带参的委托      
  5. public delegate void MyDel2(int num1, int num2);      
  6. //声明带有返值的委托      
  7. public delegate string MyDel3(string s);      
  8. //声明委托用于演示匿名方法    
  9.   public delegate string ProcessString(string s);    class Program     
  10.  {          
  11. static void Main(string[] args)        
  12.   {           
  13.    #region 委托演示                       
  14.                /*       
  15.        TestDel t = new TestDel();                
  16.         #region 简单实例化委托与调用委托        
  17.       Console.WriteLine("-----以下是简单使用委托演示--------  
  18. ");             
  19.  //t.MyMethod();       
  20. ///实例化委托,用一个方法来进行实例化         
  21.      ///该方法签名要与委托签名一致    
  22.           MyDel del = new MyDel(t.MyMethod);                    
  23.      ///调用委托          
  24.     del();        
  25.       //C#2.0后可以这种方式实例化委托          
  26.     MyDel del4 = t.MyMethod;           
  27.    del4();        
  28.      //用静态方法进行实例化     
  29.          del4 = TestDel.MyStaticMethod;      
  30.         del4();           
  31.    //以下代码效果相同        
  32.       //MyDel2 del2 = new MyDel2(t.MyMethod);            
  33.   //del2(10, 20);          
  34.     MyDel2 del2 = t.MyMethod;           
  35.    del2(10, 20);           
  36.    //MyDel3 del3 = new MyDel3(t.MyMethod);          
  37.     //Console.WriteLine(del3("abc"));         
  38.    #endregion             
  39.             #region 匿名方法实例化委托          
  40.   Console.WriteLine("-----以下是匿名方法演示--------");           
  41.    //用匿名方法实例化委托         
  42.      ProcessString p = delegate(string inputString) {            
  43.       return inputString.ToUpper();      
  44.         };      
  45.         //通过委托调用匿名方法         
  46.      Console.WriteLine(p("aaaa"));        
  47.     #endregion            
  48.   #region 委托多播演示             
  49.  Console.WriteLine("-----以下是委托多播演示--------");            
  50.   MyDel mydel1 = t.MyMethod;      
  51.         MyDel mydel2 = t.MyMethod2;       
  52.        MyDel mydel3 = TestDel.MyMethod3;      
  53.       MyDel allMyDel = mydel1 + mydel2 + mydel3;       
  54.      allMyDel();           
  55.    allMyDel -= mydel3;       
  56.        allMyDel();            
  57.   #endregion                 
  58.        #region 委托作为参数演示         
  59.      Console.WriteLine("-------以下是委托作为参数演示------");      
  60.         MyDel3 paramMyDel3 = t.MyMethod;         
  61.    TestDel.MyParamMethod("aaa", paramMyDel3);        
  62.     #endregion           
  63.    #region 委托作为返回值          
  64.     Console.WriteLine("---以下是委托作为返回值演示------");          
  65.     ///returnMyDel指向t.MyReturnMethod()的返回值          
  66.   MyDel3 returnMyDel = t.MyReturnMethod();        
  67.       ///returnMyDel指向t.MyMethod          
  68.     //MyDel3 returnMyDel = t.MyMethod;     
  69.          Console.WriteLine(returnMyDel("sssssssssssss"));        
  70.       #endregion         
  71.       */           
  72.    #endregion           
  73.    //MyReturnDelegateTest my = new MyReturnDelegateTest();       
  74.        //my.MyTest();         
  75.      MyParamDelegateTest myParam = new MyParamDelegateTest();         
  76.      myParam.AddBooks();        
  77.       myParam.MyTest();        
  78.   }    }    public class TestDel   
  79.    {    
  80.       #region 普通方法        
  81.   public static void MyStaticMethod()       
  82.    {            
  83.   Console.WriteLine("My Static Method");     
  84.      }      
  85.     public void MyMethod()     
  86.      {            Console.WriteLine("MyMethod");   
  87.        }        public void MyMethod2()        {       
  88.      Console.WriteLine("My Method 22222222222");      
  89.     }       
  90.    public static void MyMethod3()      
  91.     {          
  92.     Console.WriteLine("My Method 3333333333333");     
  93.    }        
  94.   public void MyMethod(int num1, int num2)       
  95.  {     
  96.        Console.WriteLine(num1+num2);    
  97.       }        
  98.   public string MyMethod(string s)    
  99.       {            return s.ToUpper();      
  100.     }        #endregion         
  101.  /// <summary>       
  102.    /// 委托作为方法参数      
  103.     /// </summary>        
  104.   /// <param name="s"></param>       
  105.    /// <param name="del3"></param>      
  106.     public static void MyParamMethod(string s, MyDel3 del3)   
  107.      {         
  108.      Console.WriteLine(del3(s));      
  109.     }        /// <summary>    
  110.       /// 委托作为返回值        
  111.   /// </summary>       
  112.    /// <param name="s"></param>      
  113.     /// <returns></returns>     
  114.      public MyDel3 MyReturnMethod()      
  115.     {              
  116. ///返回符合委托规范的方法        
  117.      return MyMethod;        
  118.   }    } 

委托作为参数示例:

委托作为参数

  1.   public class MyParamDelegateTest    
  2.   {      
  3.     BookDB bookDB = new BookDB();    
  4.       public void AddBooks()       
  5.  {                
  6.  bookDB.AddBook(new Book() { BookID=1,BookName="C#",Price=123,IsPaperbook=true });           
  7.  bookDB.AddBook(new Book() { BookID = 1, BookName = "C#", Price = 123, IsPaperbook = false });     
  8.  bookDB.AddBook(new Book() { BookID = 2, BookName = "ASP.Net", Price = 12, IsPaperbook = true });             
  9.  bookDB.AddBook(new Book() { BookID = 1, BookName = "ADO", Price = 23, IsPaperbook = false });   
  10.      }       
  11.    /// <summary>         
  12.  /// 用来实例化委托        
  13.   /// </summary>        
  14.   /// <param name="b"></param>       
  15.    public void TestProcessBook(Book b)     
  16.    {           
  17.  if (b.IsPaperbook)            {          
  18.       Console.WriteLine(b.BookName);           
  19.    }        }     
  20.      double total = 0;      
  21.  public void TotalPrice(Book b)    
  22.    {            total += b.Price;       
  23.  }        public void MyTest()        {                        
  24.  //ProcessBook p=TestProcessBook;             
  1.  //ProcessBook p1=TotalPrice;           
  2.    //ProcessBook p2=p+p1;         
  3.      //把方法名做为参数进行传递        
  4.       bookDB.PrintBook(TestProcessBook);      
  5.       bookDB.PrintBook(TotalPrice);        
  6.     Console.WriteLine(total);        
  7.   }    }     
  8.  public delegate void ProcessBook(Book b);  
  9.   public class BookDB    {    
  10.       public List<Book> books = new List<Book>();    
  11.     public void AddBook(Book b)     
  12.      {          
  13.     books.Add(b);       
  14.    }         
  15.  public void PrintBook(ProcessBook process)     
  16.    {          
  17.     foreach (var book in books)            {       
  18.          process  
  19. (book);            }            
  20.           }    }    public class Book     
  21.  {        public int BookID { getset; }       
  22.    public string BookName { getset; }      
  23.     public double Price { getset; }    
  24.       public bool IsPaperbook { getset; }   
  25.    } 

委托作为返回值:

委托作为返回值

  1.  public delegate int MyReturnDelegate(int num1, int num2);   
  2.  public class MyReturnDelegateTest    {        
  3. public void MyTest()      
  4.   {         
  5.    MyCalcuate myCalcuate = new MyCalcuate();        
  6.     do      
  7.       {              
  8.   Console.WriteLine("请输入符号进行以计算( + - * /)");            
  9.     string oper = Console.ReadLine();           
  10.      Console.WriteLine("请输入操作数1");       
  11.          string num1 = Console.ReadLine();          
  12.       Console.WriteLine("请输入操作数2");              
  13.   string num2 = Console.ReadLine();           
  14.      MyReturnDelegate myReturn = myCalcuate.Calcuate(oper);          
  15.       int result = myReturn(int.Parse(num1), int.Parse(num2));              
  16.   Console.WriteLine(                 
  17.    string.Format("{0}{1}{2}={3}", num1,oper,num2, result));            
  18.     Console.WriteLine("您还要继续吗?Y/N");               
  19.  //string continueFlag = Console.ReadLine();               
  20.  //if (continueFlag.ToUpper() == "N") break;            
  21. while (Console.ReadLine().ToUpper()!="N");        }    
  22. }     
  23. ublic class MyCalcuate   
  24.  {        
  25. public MyReturnDelegate Calcuate(string oper)        {            
  26. MyReturnDelegate myReturn = null;         
  27.    switch (oper)     
  28.        {                case "+":              
  29.       myReturn = delegate(int num1, int num2) { return num1 + num2; };              
  30.       break;              
  31.   case "-":                  
  32.   myReturn = delegate(int num1, int num2) { return num1 - num2; };              
  33.       break;           
  34.      case "*":                   
  35.  myReturn = delegate(int num1, int num2) { return num1 * num2; };                
  36.     break;             
  37.    case "/":          
  38.           myReturn = delegate(int num1, int num2) { return num1 / num2; };     
  39.                break;              
  40.   default:                  
  41.   break;            }     
  42.        return myReturn;       
  43.  }    } 
原文链接:http://www.cnblogs.com/yangyancheng/archive/2011/04/21/2024145.html
责任编辑:彭凡 来源: 博客园
相关推荐

2015-03-04 14:54:47

DockerIT管理基础设施

2011-06-24 14:18:40

Firefox 5

2013-12-02 14:07:02

Hadoop大数据集群

2010-05-10 11:08:28

IPv6

2020-01-17 06:12:10

物联网IOT技术

2021-01-28 10:17:54

人工智能AI机器学习

2020-06-04 13:52:00

CRM选型

2014-06-20 14:35:48

浪潮数据

2024-03-21 08:57:39

语言软件开发

2015-09-16 14:13:53

应用集成应用开发企业架构

2021-09-05 08:46:29

CSPM网络安全网络攻击

2015-05-21 10:03:04

应用标题ASO

2020-09-28 07:56:16

Python3.9Python开发

2010-05-21 09:21:48

PHPPHP开发者

2010-06-11 14:46:38

可路由协议

2011-06-14 14:04:11

测试用例

2015-01-20 11:24:52

Win 10

2017-11-30 12:23:55

IO性能RAID

2022-02-16 08:01:45

网络安全趋势

2015-01-15 09:34:28

点赞
收藏

51CTO技术栈公众号