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