学事件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApp1
{
{
delegate void Handler();//声明一个委托
class FaBuZhe//发布者类
{
public event Handler CountedADozen; //声明一个事件
public void DoCount()//触发事件的代码方法
{
CountedADozen();
}
CountedADozen();
}
}
class Dozens
{
public Dozens(FaBuZhe faBu)
{
faBu.CountedADozen += IncrementDozensCount;//在发布者私有委托里增加方法
faBu.CountedADozen += IncrementDozensCount;//在发布者私有委托里增加方法
}
void IncrementDozensCount()//事件成员被触发时要调用的方法
{
Console.WriteLine("Dozens 下的方法");
}
}
class SomeOtherClass
{
public SomeOtherClass(FaBuZhe faBu)
{
faBu.CountedADozen += DoSomething;//在发布者私有委托里增加方法
// faBu.CountedADozen -= DoSomething;
//faBu.CountedADozen +=
faBu.CountedADozen += DoSomething;//在发布者私有委托里增加方法
// faBu.CountedADozen -= DoSomething;
//faBu.CountedADozen +=
}
public void DoSomething()//事件成员被触发时要调用的方法
public void DoSomething()//事件成员被触发时要调用的方法
{
Console.WriteLine("SomeOtherClass 下的方法");
}
}
}
class Program
{
static void Main()
{
FaBuZhe faBu = new FaBuZhe(); //发布者类
Dozens dozens = new Dozens(faBu); //实例化第一个订阅者类;在dozens中 faBu.CountedADozen += IncrementDozensCount; 加了一个方法; 如果不实例化这个类,则无法运行这个类中所注册的方法。
SomeOtherClass some = new SomeOtherClass(faBu); //第二个实例,构造函数第二次 将 faBu.CountedADozen += DoSomething; 赋值给委托
Dozens dozens = new Dozens(faBu); //实例化第一个订阅者类;在dozens中 faBu.CountedADozen += IncrementDozensCount; 加了一个方法; 如果不实例化这个类,则无法运行这个类中所注册的方法。
SomeOtherClass some = new SomeOtherClass(faBu); //第二个实例,构造函数第二次 将 faBu.CountedADozen += DoSomething; 赋值给委托
faBu.DoCount(); //触发事件的代码, 实际是运行 coutadosen 这个委托,这个委托下有很多方法,这些方法将依次运行
Console.ReadKey();
Console.ReadKey();
}
}
}
0基础想学编程;在此做个记录,看一下自己代码的水平变化。