学习 坚持 委托
C#的事件是基于委托,用关键字Event修饰的委托实例我们叫事件
Eevent修饰的委托实例和普通委托实例的区别是,Event修饰的不能直接被调用,只能间接调用。类似Private
class AButton
{
//定义一个委托类型
public delegate void ButtonHandler();
//使用event定义个一个委托实例
public event ButtonHandler Click;
//按钮单击事件
public void OnClick (){
//回调委托
Click();
}
}
主函数类
class Program
{
public static void Main (string[] args)
{
AButton button = new AButton();
Program program = new Program();
button.Click += program.ButtonClick;
//这里由于委托实例用了event修饰,所以Click直接调用回报错,没有使用event修饰的委托实例可以直接调用
//button.Click();
button.OnClick();
}
private void ButtonClick()
{
Console.WriteLine("I am a strong man");
}
}