C# 中+=的使用

Haider Ali 2023年10月12日
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
作者: Haider Ali
Haider Ali avatar Haider Ali avatar

Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.

LinkedIn

相关文章 - Csharp Operator