委托(Delegate)
什么是委托
C#中的委托(Delegate)类似于C或C++中函数的指针。委托(Delegate)是存有对某个方法的引用的一种引用类型变量。引用可在运行时被改变。
委托(Delegate)特别用于实现事件和回调方法。所有的委托(Delegate)都派生自 System.Delegate 类。
总结:委托可以理解为一种数据类型,这种类型赋值需要赋一个与之对应的方法
委托的分类
有返回值
无返回值
委托的声明
委托声明决定了可由该委托引用的方法。委托可指向一个与其具有相同标签的方法。
delegate void Mydelegate(string s,int i);
如何介绍委托:MyDelegate委托指向一个void返回类型的具有一个string和一个int类型参数的方法
委托的赋值
由委托的声明决定了可给当前委托赋值的方法类型
通过以上委托,知道必须使用一个无返回值,并且参数列表是string,int类型的一个方法方可赋予这个委托
static void Method(string s,int a)
{
Console.WriteLine(s+"的年龄是"+a);
}
static void Main(string[] args)
{
MyDelegate my = Method;
my("张三",30);
Console.ReadLine();
}
委托的使用
委托的调用其实就是他所指向的方法的一个调用执行,因此委托的执行也是小括号一对,按照参数填写
实例化委托
一旦声明了委托类型,委托对象必须使用new关键字来创建,且与一个特定的方法有关。当创建委托时,传递到new语句的参数就像方法调用一样书写,但是不带有参数。
static void Main(string[] args)
{
MyDelegate my = new MyDelegate(Method);
MyDelegate my2 = new MyDelegate(Method2);
my("张三",12);
my2("李四", 22);
Console.ReadLine();
}
static void Method(string s,int a)
{
Console.WriteLine(s+"的年龄是"+a);
}
static void Method2(string s, int a)
{
Console.WriteLine(s + "的年龄是" + a);
}
系统委托
Action委托
代表了无返回值类型的委托
static void Method1()
{
Console.WriteLine("无返回值无参");
}
static void Main(string[] args)
{
Action a = Method1;
a();
Console.ReadLine();
}
如果说需要指向一个有参的无返回值方法
static void Method2(string s)
{
Console.WriteLine("它的名字叫"+s);
}
static void Main(string[] args)
{
Action<string> a2 = Method2;
a2("旺财");
Console.ReadLine();
}
使用Action委托,可以指向无返回值的方法,参数情况如果无参则直接使用action,如果有参使用Action泛型,最多容纳16个参数
Func委托
static int Method1()
{
return 100;
}
static void Main(string[] args)
{
Func<int> f = Method1;
Console.WriteLine(f());
Console.ReadLine();
}
Func委托泛型中的最后一个参数的类型永远决定着指向的方法的返回值类型
static string Method2(string a,int b)
{
return a + "的年龄是" + b;
}
static void Main(string[] args)
{
Func<string, int, string> f2 = Method2;
Console.WriteLine(f2("小明",20));
Console.ReadLine();
}
Func委托一样最多支持16个参数的方法
多播委托
委托对象可使用"+“运算符进行合并。一个合并委托调用它所合并的两个委托。只有相同类型的委托可被合并。”-"运算符可用于从合并的委托中移除组件委托。
使用委托的这个有用的特点,您可以创建一个委托被调用时要调用的方法的调用列表。这被称为委托的 多播(multicasting),也叫组播。
static void Method1(int i)
{
Console.WriteLine("数组1"+i);
}
static void Method2(int i)
{
Console.WriteLine("数字2"+i);
}
static void Method3(int i)
{
Console.WriteLine("数字3"+i);
}
static void Main(string[] args)
{
Action<int> a = new Action<int>(Method1);
a += Method2;
a += Method3;
a(4);
Console.ReadLine();
}
static void Main(string[] args)
{
Action<int> a = new Action<int>(Method1);
a = Method2;
a = Method3;
a(4);
Console.ReadLine();
}