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
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。