您的位置:首页 > 其它

Events and Delegates(事件和委托)

2015-08-22 17:08 417 查看
Introduction

One of the most interesting concepts in C# is Event-Driven approach. Though it is a simple technique, this article is here for beginners and those who are struggling to understand the event driven model.

(事件驱动是C#种最有趣的概念之一。尽管这是一个简单的技术,但本文是针对初学者和那些试图理解事件驱动模型的人们。)

Delegates

Delegation model is a process in which a task is handed over to some other process so as to accomplish it. A manager is assigned a job which could be executed by one of his subordinates. As he knows the exact location of the subordinate, he redirects or delegates the work. Here, manager is the delegate and his subordinate is the method wrapped up with the delegate.

(委托模型是在其中一个任务移交给其他处理,以便完成它的处理。经理被赋予这可以通过他的一个下级要执行的任务。当他知道下属的真实处境,他重新委派这个工作。在这里,经理是委托,他的下属就是跟这个委托联系在一起的方法。)

Delegates are the special objects in C# which are pointers to methods. It’s an interesting and amazing feature of C#. It is something that gives a name to a method signature. These are implemented as classes derived from the base class System.Delegate. It is nothing but a type like a class. But with classes, there are two distinct terms: ‘class’, which indicates the broader definition, and ‘object’, which means an instance of the class. Unfortunately, with delegates, there is only the one term. That is, when you create an instance of a delegate, what you have created is also referred to as a ‘delegate’. The syntax for defining delegates looks like this:

(在C#中,委托是指向方法的特殊对象。这是C#的一个有趣和令人惊叹的功能。这是方法签名一个名称。委托是从基类System.Delegate派生类出来的。它只不过是类似于一个类。但是对于类来说,有两个不同的方面:“类”,其指示更广泛的定义; “对象”,这意味着类的一个实例。不幸的是,对于委托来说只有一个方面。也就是说,当你创建一个委托的实例,意味着你所创建的就是一个委托。定义委托的语法如下:)

delegate <return type> <delegate name>( <parameter list> );


The important point to note here is the signature of delegates and methods. A software team manager will lead a group of people whose educational background is related to information technology and who can develop and maintain software applications. Hence, the method to be wrapped must match the signature of the delegate, otherwise would end up with a compilation error.

(这里要注意的重要一点是委托和方法的签名。一个软件团队的经理将带领一群人,他们的教育背景有关,信息技术和谁可以开发和维护的软件应用程序。因此,该方法被包裹必须与委托的签名相匹配,否则会落得一个编译错误。)

Multicast Delegate

Any manager in an organization will have one or more subordinates working under him. When a task is to be accomplished, the chief will not call each and every subordinate individually. Because, the chief does not know the specialization of all the subordinates. The chief will instruct or assign a task to the manager and the manager in turn will delegate the work to his subordinates. Obviously, any number of subordinates could be added or removed from a particular team at any point of time.

(任何管理者在一个组织都会有一个或多个下属在他手下工作。当一个任务要完成,首席不会叫每单独每一个下属。因为,首席不知道所有的下属的专业化。首席将指示或任务分配给经理,经理又将工作委托给他的下属。显然,任何数量的下属可以增加或从特定球队除去任何时间点。)

When a delegate is wrapped with more than one method, that is known as a multicast delegate. As stated above, a manager who points to more than one member is a multicast delegate. If a multicast delegate is called, it will successively call each method in order. It is derived from System.MulticastDelegate that in turn is derived from System.Delegate. System.MulticastDelegate has additional members to allow chaining of method calls together into a list.

(当委托是包裹着一个以上的方法,也就是公知的为多播委托。如上所述,管理者谁指向一个以上的成员是一个多播委托。如果一个多播委托被调用时,它会先后以调用每个方法。它从System.MulticastDelegate派生而来,而System.MulticastDelegate又是从System.Delegate而得。 System.MulticastDelegate还有其他成员,让方法的调用链连成一个列表。)

Event

Events are nothing but change of state. Assume that a software project was successfully installed in a customer’s place. Later, the maintenance department was notified by the client for some enhancements. It’s an event and which triggers the corresponding manager to take necessary actions, and he handles it by delegating the task to his subordinates. Here, make a note of two key aspects, i.e., event and event handlers. The client’s requisition for modification is ‘event’ and the subordinates who are going to execute that requisition are ‘event handlers’.

(事件就是状态的变化。假定一个软件项目成功地安装在客户的地方。后来,维修部是由客户端通知了一些改进。这是一个事件并触发相应的管理人员采取必要的行动,以及他处理它通过委派任务给他的下属。在这里,请记下两个关键方面,即事件和事件处理程序。客户端的请购单的修改是“事件”和谁是要执行该征用下属“事件处理程序”。)

Events are actually a special form of delegates. It’s a way for server applications to provide notifications to clients of that class when some interesting thing happens to an object. It is extensively used in Graphical User Interfaces (GUIs). Events are declared using delegates. Considering the aforesaid example, event is a way for a server application to allow client applications to give it delegates to methods that should be called when the event occurs. When an event occurs, the delegate(s) given to it by its client applications are invoked. The syntax to declare an event is :

(事件实际上委托的一种特殊形式。当一些有趣的事情发生在一个对象,这是一种用于服务器应用程序能够提供通知的那类客户端。它被广泛地用于图形用户界面(GUI)。事件是使用委托声明。考虑上述的例子中,事件是一种使服务器应用程序,以允许客户端应用程序给它委托在事件发生时,应该被调用的方法。当事件发生时,由它的客户端应用程序提供给它的委托(S)被调用。声明事件的语法如下:)

event < delegate type name > < event name >;


Stock Management Module

Here is the code which has four events and as many event handlers as you wish. This module contains 4 classes

viz., CInventory, CInventoryManager, CInventoryWatcher, and CStockentry. Before going into the module, I would like to touch the stock management system. In the inventory control system of any item, we have stock level, reorder level, minimum and maximum level. When stock is beyond the maximum level, the purchase department should be informed to stop ordering new items. Likewise, when the stock reaches either minimum or reorder level, we raise the purchase order, and the same should be authorized so as to purchase new items. This is what this code explains.

(正如你所愿,下面是一个有四个事件和尽可能多的事件处理程序的代码。该模块包含4类即,CInventory,CInventoryManager,CInventoryWatcher和CStockentry。在走进模块之前,我想触摸一下库存管理系统。在任何项目的库存控制系统,我们有库存水平,订货点水平,最低和最高水平。当股价超出了最高水平,采购部门应告知停止订购新项目。同样,当股票达到或者最小或订货点水平,我们提高了采购订单,同样应被授权,以购买新的项目。这是该代码解释。)

private string _sStockName;
private int _iStock;

public string StockName
{get{return _sStockName;} set{ _sStockName=value;}}

public int Stock
{get{return _iStock;}set{_iStock += value;}}


CInventoryManager is the event publisher which has four events viz., OnInventoryChange, OnMaxLevel,OnROLevel, and OnMinLevel. Whenever there is a change in the stock value, OnInventoryChange will be triggered. Other events are raised based on a particular state. If the stock value is less than or equal to 20,OnMinLevel event will be triggered. If the stock value is less than or equal to 50, then OnROLevel event will be triggered. If the stock value is greater than or equal to 100, then OnMaxLevel event will be triggered

(CInventoryManager是事件发布者,它有四个事件即,OnInventoryChange,OnMaxLevel,OnROLevel和OnMinLevel。每当有股票价值的变化,OnInventoryChange将被触发。其他事件基于特定状态上升。如果股票值小于或等于20,OnMinLevel事件将被触发。如果股票值小于或等于50,则OnROLevel事件将被触发。如果股票值大于或等于100,则OnMaxLevel事件将被触发。)

public delegate void InvDel(object source,CInventory inventory);

public event InvDel OnInventoryChange;

public event InvDel OnMaxLevel;

public event InvDel OnROLevel;

public event InvDel OnMinLevel;


CInventoryWatcher class is the event subscriber where event handlers are placed. Here, you could see how multicast delegates are defined and executed. In the constructor of this class, you will find the event subscriptions by instantiating InvDel delegate which is located in CInventoryManager class. When OnROLevel event occurs, two event handlers subscribed to it will fire. Which means, whenever the stock value reaches reorder level, we have to create purchase order, and the purchased order should be authorized.

(CInventoryWatcher类是事件的用户,其中的事件处理程序被放置。在这里,你可以看到多播委托如何定义和执行。在这个类的构造函数,你将通过实例InvDel委托其位于CInventoryManager类找到事件订阅。当OnROLevel事件发生时,订阅了它两个事件处理程序将闪光。这意味着,每当股市值达到订货点水平,我们必须创建采购订单,而购令应该被授权。)

inventoryManager.OnInventoryChange += new CInventoryManager.InvDel(OnChange);
inventoryManager.OnROLevel += new CInventoryManager.InvDel(CreatePO);
inventoryManager.OnMaxLevel += new CInventoryManager.InvDel(CreateMaxMsg);
inventoryManager.OnMinLevel += new CInventoryManager.InvDel(CreateMinMsg);
inventoryManager.OnROLevel += new CInventoryManager.InvDel(AuthPO);


Running the sample application

Run the sample application. In the stock entry form, enter the name of the item and the new stock value. I have coded the values for minimum, maximum, and reorder level. That is, Minimum level =20, Maximum Level =100 and Reorder Level = 50. If you want, you can change these values in the StockLevels.cs file. Please look at the source code for more clarifications. The whole task could be achieved in a single file, but to understand event generators and even handlers, I have separated it.

I would appreciate if you could give your valuable feedback after reading this article.

(运行示例应用程序。在股票报名表,输入项目的名称和新的股票价值。我已编码的最小值,最大值,和重新排序级的值。也就是说,最低级=20,最大水平=100和重新排序等级=50。如果你愿意,你可以在StockLevels.cs文件中改变这些值。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: