ホームページ  >  記事  >  バックエンド開発  >  C# のイベントとは何ですか?

C# のイベントとは何ですか?

王林
王林転載
2023-09-14 16:41:031065ブラウズ

C# 中的事件是什么?

イベントは、キーの押下、クリック、マウスの動きなどのユーザーのアクション、またはシステム生成の通知などの特定のイベントです。

イベントは、同じクラスまたは他のクラスのデリゲートを使用するイベント ハンドラーを持つクラスで宣言され、発生します。イベントを含むクラスは、イベントの発行に使用されます。

クラスでイベントを宣言するには、まずイベントのデリゲート型を宣言する必要があります。たとえば、

public delegate string myDelegate(string str);

さあ、イベントを宣言します -

event myDelegate newEvent;

次に、C# でイベントを処理する例を見てみましょう -

Example

オンライン デモ

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!

以上がC# のイベントとは何ですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はtutorialspoint.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。