C# 中的委托(Delegate)类似于 C 或 C++ 中函数的指针。委托(Delegate) 是存有对某个方法的引用的一种引用类型变量。引用可在运行时被改变。(定义来自于菜鸟教程)
C#委托声明的基本格式:delegate 返回类型 委托类型名 签名(含ref&out)。
C#委托有如下特征:1.必须在被用来创建变量及类型的对象之前声明;2.没有方法主体;
C#委托有两种实例化方法,在如下的代码中可以体现:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
delegate int text(int a); //创建委托
namespace Delegate
{
class Program
{
int aab(int a)
{
a += 1;
return a;
}
int abb(int a)
{
a += 2;
return a;
}
static void Main(string[] args)
{
int a = 1;
Program abc = new Program();
text ab = new text(abc.aab); //一般的实例化格式
text ba = abc.abb; //默认的实例化格式
Console.WriteLine("{0}",ab(a));
Console.WriteLine("{0}", ba(a));
Console.ReadLine();
}
}
}
C#委托的多播(multicasting)
C#委托的多播,在有的书上也被称作委托的组合,委托对象可使用 “+” 运算符进行合并。一个合并委托调用它所合并的两个委托。只有相同类型的委托可被合并。”-” 运算符可用于从合并的委托中移除组件委托。,在如下的代码中可以体现
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
delegate int text(ref int a); //创建委托
namespace Delegate
{
class Program
{
int aab(ref int a)
{
a += 1;
return a;
}
int abb(ref int a)
{
a += 2;
return a;
}
static void Main(string[] args)
{
int a = 1;
Program abc = new Program();
text aabb;
text ab = new text(abc.aab); //一般的实例化格式
text ba = abc.abb; //默认的实例化格式
aabb = ab;
aabb += ba; //委托的多播
Console.WriteLine("{0}",aabb(ref a));
Console.ReadLine();
}
}
}