委托 事件
1.定义委托 : 方法定义前 加 delegate
public delegate void NoReturnNoPara();
public delegate void NoReturnWithPara(int x, int y);//1 声明委托
public delegate int WithReturnNoPara();
public delegate string WithReturnWithPara(out int x, ref int y);
2. 实例化委托 要求传入完全吻合的方法
NoReturnNoPara method = new NoReturnNoPara(this.DoNothing)
private void DoNothing()
{
Console.WriteLine("This is DoNothing");
}
3.调用委托
NoReturnWithPara method = new NoReturnWithPara(this.DoNothingPara);
method.Invoke(1,2)
private void DoNothingPara(int x, int y)
{
Console.WriteLine("This is DoNothing");
}
4.泛型委托
Action act1 = () => { };
Action<int> act2 = i => { };//如果只有一个参数 可以去掉小括号
Action<int, string, int, int, string, int, int, string, int, int, string, int, int, string, int, string> act17 = null
Func<int> fun1 = () => 123; //如果方法体只有一行,可以去掉大括号和分号 和return
Func<int, string> func2 = i => i.ToString();
Func<int, string, int, int, string, int, int, string, int, int, string, int, int, string, int, string, MyDelegate> fun17 = null;
5.多播委托
+= 表示向一个委托实例里面添加方法,形成方法链,invoke的时候,按添加顺序执行
Action act = new Action(this.DoNothing);
act += this.DoNothing;
act += DoNothingStatic;
act += other.DoNothing;
act += new OtherClass().DoNothing;
act += OtherClass.DoNothingStatic;
act += () => Console.WriteLine("这里是lambda表达式");
act.Invoke();
act.GetInvocationList().Length
act.BeginInvoke(null, null);//委托里面只能有一个方法
foreach (Action item in act.GetInvocationList())
{
item.BeginInvoke(null, null);
}
-= 表示向一个委托实例里面移除方法,从方法链尾部开始匹配,遇到第一个完全吻合的,移除且只移除一个;没有匹配的,也不异常
act -= this.DoNothing;
act -= DoNothingStatic;
act -= other.DoNothing;
act -= new OtherClass().DoNothing;
act -= OtherClass.DoNothingStatic;
act -= () => Console.WriteLine("这里是lambda表达式");
act.Invoke();
5.委托简化 ,lambda 表达式
1. NoReturnWithPara method = new NoReturnWithPara(this.DoNothingPara);
2.NoReturnWithPara method = new NoReturnWithPara(delegate(int x, int y) {Console.WriteLine(iNum);Console.WriteLine("This is DoNothing");});
3.NoReturnWithPara method = new NoReturnWithPara((int x, int y) => //goes to lambda表达式 本质是匿名方法 也就是个方法
{
Console.WriteLine(iNum);
Console.WriteLine("This is DoNothing");
}
4.NoReturnWithPara method = new NoReturnWithPara((x, y) =>
// /参数类型可以去掉,因为约束的限制
{
Console.WriteLine("This is DoNothing");
});
5.NoReturnWithPara method = new NoReturnWithPara((x, y) =>
//如果方法体只有一行,可以去掉大括号和分号
Console.WriteLine("This is DoNothing")
);
6. NoReturnWithPara method = (x, y) => Console.WriteLine("This is DoNothing");
6. 事件
public event Action MiaoEventHandlerEvent; 在外部赋值 在内部调用
//事件就是委托的实例,增加event关键字,防止外部直接invoke和赋值
//事件和委托的区别联系?
//事件就是委托的实例,委托是一个类型 而事件是委托类型的一个实例
//Student是一个类型 而大山是Student类型的一个实例
public void MiaoActionEvent()
{
Console.WriteLine("{0} MiaoActionEvent", this.GetType().Name);
if (this.MiaoEventHandlerEvent != null)
{
this.MiaoEventHandlerEvent.Invoke();//子类都没办法invoke
}
}