我一直在尝试记住如何在C#中编写事件和事件处理程序一段时间.每当我想在互联网上引用教程时,他们往往都很冗长.
问题是如何在C#中编写事件和事件处理程序?你有一个代码示例,很容易说明如何写这样的?
解决方法
它们不必冗长:
// declare an event: public event EventHandler MyEvent; // raise an event: var handler = MyEvent; if(handler != null) handler(this,EventArgs.Empty); // consume an event with an anon-method: obj.MyEvent += delegate { Console.WriteLine("something happened"); }; // consume an event with a named method: obj.MyEvent += SomeHandler; void SomeHandler(object sender,EventArgs args) { Console.WriteLine("something happened"); }
什么是麻烦的?