HOWTO · Csharp
C# 中+=的使用
本文介紹了 C# 中加等號 += 運算子的使用。
本指南將瞭解 C# 中的 += 運算子。C# 中的 += 與其他程式語言中的不同。
它也可以用作賦值運算子,就像所有其他語言一樣。我們將看到它在 C# 中的其他用途。
讓我們深入瞭解一下。
在 C# 中使用 += 作為 EventHandler
在 C# 語言中,運算子 += 指定應呼叫的方法以響應事件。
這些型別的方法也稱為事件處理程式。EventHandler 是 C# 中的一個類,具有內建方法。
在下面的程式碼中,我們製作了一個自定義事件處理程式類。看一看。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OpreationEvents {
class MyEvents {
public event EventHandler ApplicationEvent // Builtin Methods
{
add // writing custom event handler class.
{
Console.WriteLine("Add operation EVENT");
}
remove {
Console.WriteLine("Remove operation EVENT");
}
}
static void Main() {
MyEvents temp = new MyEvents();
temp.ApplicationEvent += new EventHandler(temp.Trigger); // Assging method to event;
temp.ApplicationEvent -= null; // Removing Event Methods
Console.Read();
}
void Trigger(object sender, EventArgs e) {
Console.WriteLine("I will Trigger on Event Happening");
}
}
}
void 方法 trigger() 分配給上述程式碼中的事件。每當該事件發生時,它將觸發 trigger() 函式。
我們還可以使用 -= 運算子來刪除操作事件。這與我們在 += 運算子中學到的相反。
輸出:
Add operation EVENT
Remove operation EVENT