如何在 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!

更新于: 20-6 月 -2020

302 次浏览

开启你的 职业生涯

完成课程即可获得认证

开始
广告
© . All rights reserved.