最典型的事件例子,猫叫了(事件源),老鼠跑了(事件订阅者),惊醒主人(事件订阅者

源代码:

class Program
{
	static void Main(string[] args)
	{
		Cat cat = new Cat();

		cat.catEvent += Mouse;//订阅猫事件
		cat.catEvent += Person;//订阅人事件

		cat.Cry("猫:喵~");//猫叫的动作,触发事件

		Console.ReadKey();
	}

	private static void Person(object sender, EventArgs e)
	{
		Console.WriteLine("人:大半夜的不睡觉,叫唤个啥呢?~");
	}

	private static void Mouse(object sender, EventArgs e)
	{
		Console.WriteLine("猫:快跑~");
	}
	}

	public class Cat
	{
		public event EventHandler<EventArgs> catEvent;

		public void Cry(string msg)
		{
		Console.WriteLine(msg);

		catEvent(this, new EventArgs());
	}
}

  

执行结果:

C#事件订阅及触发例子

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-07
  • 2021-07-30
  • 2021-10-17
  • 2021-08-14
猜你喜欢
  • 2021-11-06
  • 2021-11-04
  • 2022-12-23
  • 2021-07-12
  • 2022-12-23
  • 2021-11-16
相关资源
相似解决方案