跳转到主内容
新派编程网 - 新潮编程理念,全新技术课堂!

C# 中的事件是什么?

事件是用户操作,例如按键、单击、鼠标移动等,或某些事件,例如系统生成的通知。 事件在类中声明和引发,并与在同一类或其他类中使用委托的事件处理程序。包含事件的类用于发布事件。 要在类中声明事件,首先必须声明该事件的委托类型。例如,
public delegate string myDelegate(string str);
现在,声明一个事件 −
event myDelegate newEvent;
现在让我们看一个在C#中处理事件的示例 − 示例 在线演示
using System; namespace Demo { public delegate string myDelegate(string str); class EventProgram { event myDelegate newEvent; public EventProgram() { this.newEvent += new myDelegate(this.WelcomeUser); } public string WelcomeUser(string username) { return "Welcome " + username; } static void Main(string[] args) { EventProgram obj1 = new EventProgram(); string result = obj1.newEvent("My Website!"); Console.WriteLine(result); } } }
输出
Welcome My Website!

相关文章