如何在 C# 中声明事件?

csharpprogrammingserver side programming更新于 2025/5/30 16:37:17

事件是用户操作,例如按键、点击、鼠标移动等,或某些事件,例如系统生成的通知。

事件在类中声明和引发,并使用同一类或其他类中的委托与事件处理程序相关联。包含事件的类用于发布事件。

要在类中声明事件,首先必须声明事件的委托类型。例如,

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!

相关文章