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
