1.委托是一种数据类型,并且委托也是引用类型,委托本质也是一个类,这个类比较特殊,指向方法(可以通过反编译得出)
2.委托的级别和类相同
3.delegate用于声明委托
public delegate void MyDelegate(); //声明一个无返回值的委托
4.方法的签名包括返回值和参数
5.多播委托又叫委托链
Walk,Kill 和 SayHello是方法
MyDelegate myDel = Walk;
// myDel();
//Walk();//两者结果想同
myDel += Kill;//多播委托【委托链】
myDel += new Japaness().SayHello;
myDel();
6.用委托来写日志
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System. IO;
namespace 日志
{
public delegate void WriteLogDelegate(string msg);//声明委托
class Program
{
static void Main(string[] args)
{
WriteLog("张三在IP为127.0.0.1的地址登录",LogInText);
Console.ReadKey();
}
public static void WriteLog(string msg,WriteLogDelegate del)
{
del(msg);
}
public static void LogInConsole(string msg)
{
Console.WriteLine("----------------------------");
Console.WriteLine(DateTime.Now.ToString());
Console.WriteLine(msg);
}
public static void LogInText(string msg)//写入文档中,用文件操作
{
File.WriteAllText("log.txt","-------------------"+DateTime.Now.ToString()+msg);
}
}
}
7.ctor是指构造函数
8.下面这两行是等价的
MyDelegate Mydel = SayHello;
Mydel();
MyDelegate md = new MyDelegate(SayHello);//与前一行是等价的
md();
9.在使用委托时,直接md()就相当于使用了md.Invoke(),(可反编译得出)
10.委托链在执行时是安装你给委托绑定方法的顺序来依次执行,但还不能依赖这个顺序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
public delegate void MyDelegate();
public delegate int YourDelegate(int i, int j);
class Program
{
static void Main(string[] args)
{
MyDelegate md = new MyDelegate(SayHello);
md += PlayBascketball;
md += Sleep;
md -= PlayBascketball;//-=就是把一个方法从委托链上卸载了
md.Invoke();
}
public static void SayHello()
{
Console.WriteLine("哈哈");
}
public static void PlayBascketball()
{
Console.WriteLine("打篮球");
}
public static void Sleep()
{
Console.WriteLine("huhuhu");
}
结果为:
哈哈
huhuhu
11委托中如果有返回值,通过委托只能的到最后绑定的那个方法的返回值
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication4
{
public delegate int YourDelegate(int i, int j);
class Program
{
static void Main(string[] args)
{
YourDelegate yd = new YourDelegate(Add);
yd += Jian;
yd += Mul;
int sum = yd.Invoke(1, 2);
Console.WriteLine(sum);
Console.ReadKey();
}
public static int Add(int i, int j)
{
return i + j;
}
public static int Jian(int i, int j)
{
return i - j;
}
public static int Mul(int i, int j)
{
return i * j;
}
}
}
结果为:2
11.尽量少使用自定义委托,尽量使用系统定义的委托。