我正在读一本关于C#的书,它有关于复合赋值的说法(例如+ =, - =,* =,/ =,<< =,>> =):
此规则的一个微妙的例外是事件,我们在第4章中描述:此处的+ =和 - =运算符被特殊处理并映射到事件的添加和删除访问器。
任何人都可以用简单的英语解释这意味着什么吗?我还没到第4章。
答案 0 :(得分:6)
通常情况下,+=
会将右侧的表达式/变量添加到左侧的表达式/变量,并将结果分配到左侧。
// if a = 4, after this statement, a would be 5
a += 1;
但是如果带有+=
的表达式的左侧是一个事件,那么情况并非如此,但它将是右侧的事件处理程序,它被添加到列表中该事件的事件处理程序。
// whereas on the below statement someEventHandler is added to the collection of event handlers for the 'OnSomeEvent' event
self.OnSomeEvent += someEventHandler
答案 1 :(得分:3)
它只是意味着+ =将事件方法附加到例如控制而不是添加(例如算术加法)
// += as in arithmetic addition
int i = 3;
i += 1; // i now outputs 4
// += as in programmatically attaching an event to a control
Button btn = new Button();
btn.Click += new EventHandler(btn_Click);
private void btn_Click(object obj) { ... ; }
看到区别?
答案 2 :(得分:1)
C#中有一个委托的概念,它可以指向一个方法。您可以将事件视为特殊类型的代理。您可以add
(或remove
)对事件采用多种方法。它允许您在发生特定事件时执行指定的方法。
删除在Console和MessageBox上显示删除结果的文件时的一个简单示例。
// This is the delegate. Any instance with DeletedEventHandler type
// can point a method which returns voids and accepts parameters (object,bool)
public delegate void DeletedEventHandler(object sender, bool deleted);
public class FileDeleter
{
private DeletedEventHandler onDelete;
public event DeletedEventHandler OnDelete
{
// The add and remove accessors
add { onDelete += value; }
remove { onDelete -= value; }
}
public void Delete(string filePath)
{
try
{
File.Delete(filePath);
RaiseOnDelete(true);
}
catch
{
RaiseOnDelete(false);
}
}
private void RaiseOnDelete(bool deleted)
{
if (onDelete != null)
onDelete(this, deleted); // all methods added executes here
}
}
public void TestMethod()
{
FileDeleter deleter = new FileDeleter();
// Note that both ShowDeleteInfoWindows and ShowDeleteInfoConsole are in form of void(object,bool) which is compatible with DeletedEventHandler
deleter.OnDelete += new DeletedEventHandler(DeletedOnConsole);
deleter.OnDelete += new DeletedEventHandler(ShowDeleteInfoWindows);
deleter.Delete(@"C:\test.txt");
}
private void ShowDeleteInfoConsole(object deleter, bool isDeleted)
{
Console.WriteLine(isDeleted);
}
private void ShowDeleteInfoWindows(object deleter, bool isDeleted)
{
MessageBox.Show(isDeleted.ToString());
}