我理解事件的目的,特别是在创建用户界面的上下文中。我认为这是创建事件的原型:

public void EventName(object sender, EventArgs e);

事件处理程序做什么,为什么需要它们,以及如何创建一个?


当前回答

另一件需要知道的事情是,在某些情况下,当你需要低级别耦合时,你必须使用委托/事件!

如果您想在应用程序的多个地方使用一个组件,您需要使组件具有低级别的耦合,并且必须将特定的无关逻辑委托到组件之外!这确保了您有一个解耦的系统和更清晰的代码。

在SOLID原则中,这是“D”,(依赖倒置原则)。

也被称为“IoC”,反转控制。

你可以用事件、委托和DI(依赖注入)来创建“IoC”。

在子类中访问方法很容易。但是从子类中访问父类中的方法更加困难。你必须把父引用传递给子引用!(或使用DI接口)

委托/事件允许我们在没有引用的情况下从子对象通信到父对象!

在上面的图中,我没有使用委托/事件,并且父组件B必须有父组件a的引用来执行方法a中无关的业务逻辑(高级别耦合)。

使用这种方法,我将不得不放置所有使用组件B的组件的所有引用!:(

在上面的图中,我使用委托/事件,组件B不必知道a(低级别耦合)

您可以在应用程序的任何地方使用组件B !

其他回答

发布者:事件发生的地方。发布者应该指定类使用哪个委托,并生成必要的参数,将这些参数和自身传递给委托。

订阅者:响应发生的地方。订阅者应指定响应事件的方法。这些方法应该采用与委托相同类型的参数。订阅者然后将此方法添加到发布者的委托。

因此,当事件在publisher中发生时,delegate将收到一些事件参数(数据等),但publisher不知道所有这些数据将会发生什么。订阅者可以在自己的类中创建方法来响应发布者类中的事件,这样订阅者就可以响应发布者的事件。

这实际上是一个事件处理程序的声明——一个在触发事件时被调用的方法。要创建一个事件,你可以这样写:

public class Foo
{
    public event EventHandler MyEvent;
}

然后你可以像这样订阅这个事件:

Foo foo = new Foo();
foo.MyEvent += new EventHandler(this.OnMyEvent);

OnMyEvent()的定义如下:

private void OnMyEvent(object sender, EventArgs e)
{
    MessageBox.Show("MyEvent fired!");
}

每当Foo触发MyEvent,那么你的OnMyEvent处理程序将被调用。

你不必总是使用EventArgs的实例作为第二个参数。如果你想包含额外的信息,你可以使用一个从EventArgs派生的类(根据惯例EventArgs是基类)。例如,如果你查看WinForms中的Control上定义的一些事件,或者WPF中的FrameworkElement上定义的一些事件,你可以看到将附加信息传递给事件处理程序的事件示例。

我最近做了一个如何在c#中使用事件的例子,并发布在我的博客上。我用了一个简单的例子,尽量把它讲清楚。如果它可能帮助任何人,这里是:http://www.konsfik.com/using-events-in-csharp/

它包括描述和源代码(带有大量注释),主要关注事件和事件处理程序的正确使用(类似模板)。

一些要点是:

Events are like "sub - types of delegates", only more constrained (in a good way). In fact an event's declaration always includes a delegate (EventHandlers are a type of delegate). Event Handlers are specific types of delegates (you may think of them as a template), which force the user to create events which have a specific "signature". The signature is of the format: (object sender, EventArgs eventarguments). You may create your own sub-class of EventArgs, in order to include any type of information the event needs to convey. It is not necessary to use EventHandlers when using events. You may completely skip them and use your own kind of delegate in their place. One key difference between using events and delegates, is that events can only be invoked from within the class that they were declared in, even though they may be declared as public. This is a very important distinction, because it allows your events to be exposed so that they are "connected" to external methods, while at the same time they are protected from "external misuse".

要理解事件处理程序,您需要理解委托。在c#中,您可以将委托视为指向方法的指针(或引用)。这很有用,因为指针可以作为值传递。

委托的核心概念是它的签名或形状。即(1)返回类型和(2)输入参数。例如,如果我们创建一个委托void MyDelegate(object sender, EventArgs e),它只能指向返回void的方法,并接受一个对象和EventArgs。有点像一个方洞和一个方钉子。因此,我们说这些方法与委托具有相同的签名或形状。

So knowing how to create a reference to a method, let's think about the purpose of events: we want to cause some code to be executed when something happens elsewhere in the system - or "handle the event". To do this, we create specific methods for the code we want to be executed. The glue between the event and the methods to be executed are the delegates. The event must internally store a "list" of pointers to the methods to call when the event is raised.* Of course, to be able to call a method, we need to know what arguments to pass to it! We use the delegate as the "contract" between the event and all the specific methods that will be called.

因此默认的EventHandler(以及许多类似的)表示方法的特定形状(同样是void/object-EventArgs)。当你声明一个事件时,你是在说该事件将调用哪种形状的方法(EventHandler),通过指定一个委托:

//This delegate can be used to point to methods
//which return void and take a string.
public delegate void MyEventHandler(string foo);

//This event can cause any method which conforms
//to MyEventHandler to be called.
public event MyEventHandler SomethingHappened;

//Here is some code I want to be executed
//when SomethingHappened fires.
void HandleSomethingHappened(string foo)
{
    //Do some stuff
}

//I am creating a delegate (pointer) to HandleSomethingHappened
//and adding it to SomethingHappened's list of "Event Handlers".
myObj.SomethingHappened += new MyEventHandler(HandleSomethingHappened);

//To raise the event within a method.
SomethingHappened("bar");

(*这是。net中事件的关键,它揭开了“魔法”的面纱——一个事件实际上只是一组具有相同“形状”的方法。列表存储在事件所在的位置。当事件被“引发”时,它实际上只是“遍历这个方法列表并调用每个方法,使用这些值作为参数”。分配事件处理程序只是将您的方法添加到要调用的方法列表的一种更漂亮、更简单的方式)。

文章中有很棒的技术答案!我没有任何技术上的补充。

在语言和软件中出现新功能的主要原因之一是市场营销或公司政治!:-)这绝不能被低估!

我认为这也适用于代表和活动!我发现它们很有用,为c#语言增加了价值,但另一方面,Java语言决定不使用它们!他们认为无论你用委托解决什么问题,你都可以用语言的现有特性来解决,比如接口。

2001年左右,微软发布了。net框架和c#语言,作为Java的竞争解决方案,所以拥有Java没有的新功能是件好事。