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