委托是一个类型
事件是委托的一个实例 加了event关键字
Student类
public class Student
{
public event MyDelegate.Delegate1 eventDe;//预先创建事件 下面用
public void DelegateInvoke()
{
eventDe.Invoke();
}
public int Id { get; set; }
public string Name { get; set; }
public void ShowStudent()
{
Console.WriteLine("ShowStudent");
}
public static void StaticShow()
{
Console.WriteLine("StaticShow");
}
}
功能展示主要在这里
MyDelegate类
public class MyDelegate
{
public delegate void Delegate1();
public delegate void Delegate2(string name);
public delegate int Delegate3();
public delegate string Delegate4(string name);
public Delegate1 dele1;//预先创建委托 下面用
public event Delegate1 Myevent;//预先创建事件 下面用
public void Show()
{
{
//传入本类中的非静态方法
Delegate1 de = new Delegate1(this.SayHi);
de.Invoke();
//de(); //这种调用方式也可以
}
{
//传入本类中的静态方法
Delegate1 de = new Delegate1(MyDelegate.SayHellow);
de.Invoke();
}
{
//传入其他类中 非静态方法
Student stu = new Student()
{
Id = 1,
Name = "张三丰"
};
Delegate1 de = new Delegate1(stu.ShowStudent);
de.Invoke();
}
{
//传入其他类中 静态方法
Delegate1 de = new Delegate1(Student.StaticShow);
de.Invoke();
}
{
//有参数无返回值调用
Delegate2 de = new Delegate2(this.SayName);
de.Invoke("张三丰");
}
{
//无参有返回值
Delegate3 de = new Delegate3(this.ReturnIntNumber);
Console.WriteLine(de.Invoke());
}
{
//有参有返回值
Delegate4 de = new Delegate4(this.ReturnName);
Console.WriteLine(de.Invoke("张三丰"));
}
{
//多播委托 添加方法 多播委托无法异步
Delegate1 de = new Delegate1(Student.StaticShow);
de += this.SayHi;
de += MyDelegate.SayHellow;
de += new Student().ShowStudent;
//多播委托 -方法
//-方法会在方法列表里面 从下到上逐个检查 如果存在 则去掉,如果不存在 也不会报错
de -= this.SayHi;
de.Invoke();
}
{
//遍历方法多播委托 逐个Invoke
//好处:
//1、可通过逐个调用在调用前后添加其他功能
//2、可以经过逐个调用实现异步
Delegate1 de = new Delegate1(Student.StaticShow);
de += this.SayHi;
de += MyDelegate.SayHellow;
de += new Student().ShowStudent;
foreach (Delegate1 dele in de.GetInvocationList())
{
//这里可以添加其他功能
dele.Invoke();//可以实现异步
}
}
{
/*
*总结
*委托是一个类型
*事件是委托的一个实例
*因为加了event关键字 做了一个权限控制,保证了外面不能赋值和调用
*/
//委托 和事件的对比
//最上面已经创建好了一个Delegate1类型委托
//通过上面创建的委托可以直接进行添加方法 和卸载方法
dele1 += this.SayHi;
dele1 += Student.StaticShow;
dele1 -= this.SayHi;
dele1 = this.SayHi;//也可以直接进行重新赋值 赋值后 前面的都会被覆盖掉
dele1.Invoke();
//下面看一下事件 本类中已经创建好了一个Delegate1类型事件 eventDe
Myevent += this.SayHi;
Myevent -= this.SayHi;//添加和卸载方法都是没有问题的
Myevent = this.SayHi;//可以重新赋值
Myevent.Invoke();//可以直接调用
//下面看一下别的类当中的事件 Student中创建好了一个事件
Student stu = new Student()
{
Id = 1,
Name = "卡卡西"
};
stu.eventDe += this.SayHi;//添加事件 没有问题
stu.eventDe -= this.SayHi;//卸载事件 没有问题
stu.eventDe += this.SayHi;//添加事件 没有问题
// stu.eventDe = null; //赋值不可以
// stu.eventDe = this.SayHi;//赋值不可以
// stu.eventDe.Invoke(); //也不可以Invoke()
stu.DelegateInvoke();//只能通过创建该事件的类中的方法 进行Invoke
}
}
private void SayHi()
{
Console.WriteLine("无参无返回值方法1");
}
public static void SayHellow()
{
Console.WriteLine("无参无返回值方法2");
}
public void SayName(string name)
{
Console.WriteLine("我的名字是{0}", name);
}
public int ReturnIntNumber()
{
return 1;
}
public string ReturnName(string name)
{
return name;
}
}
欢迎大家加我QQ交流