深入理解C#之委托(delegate)


  C#委托类似C语言中的函数指针.

一, C# 委托的4个条件:

1.声明委托类型     delegate int IntProcess(int num);

2.必须有一个方法包含了要执行的代码 (返回值和形参列表个数&类型必须和声明的Delegate 完全一致)

  static int PrintIntNum(int num)

  {
    System.Console.WriteLine("Gavin Study Delegate {0}", num);
    return 1;
  }  

3.创建委托实例  

      TestIntDelegate = new IntProcess(Program.PrintIntNum);  

4.调用委托实例

    TestIntDelegate.Invoke(1000);

    TestIntDelegate(90);

二,合并删除委托

     1. 合并多个委托,可以采用Delegate.Combine,但是很少用,一般使用+或者+=操作符

     2.删除某个委托,可以采用Delegate.Remove,但是很少用,一般使用-或者-=操作符

     3.多个委托合并之后,会顺序执行,仅仅返回最后一个委托实例的返回值;如果某一委托实例异常,则后面的委托实例不执行

三,SourceCode

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

delegate int IntProcess(int num); // 声明委托类型     

namespace TestDelegate
{
  class Program
  {
    private int? Num; 

    public Program(int? num = null)
    {
      Num = num;
    }

    static int PrintIntNum(int num) // 有一个方法包含了要执行的代码
    {
      System.Console.WriteLine("Gavin Study Delegate {0}", num);
      return 1;
    }

    public int HelloIntNum(int num) // 有一个方法包含了要执行的代码
    {
      System.Console.WriteLine("Gavin HelloIntNum Delegate {0}, {1}", num, Num);
      return 2;
    }

    static void Main(string[] args)
    {
      IntProcess TestIntDelegate, TestInt, CommonDelegate;

      TestIntDelegate = new IntProcess(Program.PrintIntNum); //创建委托实例
      TestIntDelegate(5);  //调用委托实例
      TestIntDelegate(90); //调用委托实例
      TestIntDelegate.Invoke(1000); //调用委托实例
      Console.ReadKey();

      Program instance = new Program(55);
      TestInt = new IntProcess(instance.HelloIntNum);   // .创建委托实例
      TestInt(88); //调用委托实例
      int returnInt = TestInt.Invoke(9999); //调用委托实例
      System.Console.WriteLine("Gavin Study returnInt {0}", returnInt);

         Console.ReadKey();

      CommonDelegate = TestIntDelegate + TestInt; //委托合并

      int returnNum = CommonDelegate(8888); ////委托合并返回值
      System.Console.WriteLine("Gavin Study returnNum {0}", returnInt);
      Console.ReadKey();
      CommonDelegate -= TestIntDelegate;// //委托移除
      CommonDelegate(777);
      Console.ReadKey();

    }
  }
}

 

运行结果:

 

Gavin Study Delegate 5
Gavin Study Delegate 90
Gavin Study Delegate 1000
Gavin HelloIntNum Delegate 88, 55
Gavin HelloIntNum Delegate 9999, 55
Gavin Study returnInt 2
Gavin Study Delegate 8888
Gavin HelloIntNum Delegate 8888, 55
Gavin Study returnNum 2
Gavin HelloIntNum Delegate 777, 55


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM