在C#中的不同类提高一类的事件 [英] Raise an event of a class from a different class in C#

查看:114
本文介绍了在C#中的不同类提高一类的事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,EventContainer.cs,其中包含一个事件,说:

 公共事件的EventHandler AfterSearch; 



我有另一个类,EventRaiser.cs。我该如何提高(而不是处理)从这个类上面说的事件?



引发的事件将依次调用在EventContainer类事件的处理程序。像这样的东西(这显然是不正确的):

  EventContainer的obj =新EventContainer(); 
的RaiseEvent(obj.AfterSearch);


解决方案

这是不可能的,事件只能从上升在类中。如果你能做到这一点,它会破坏事件(能够上升从类的内部状态的变化)的目的。我想你是误会事件的功能 - 一个事件类中定义和其他人可以通过做



obj.AfterSearch +订阅它=处理器; (其中处理器是根据 AfterSearch 的签名的方法)。一个是能够​​订阅从外面就好了事件,但它只能从类定义它的内部增长。


I have a class, EventContainer.cs, which contains an event, say:

public event EventHandler AfterSearch;

I have another class, EventRaiser.cs. How do I raise (and not handle) the above said event from this class?

The raised event will in turn call the handler of the event in the EventContainer class. Something like this (this is obviously not correct):

EventContainer obj = new EventContainer(); 
RaiseEvent(obj.AfterSearch);

解决方案

This is not possible, Events can only be risen from inside the class. If you could do that, it would defeat the purpose of events (being able to rise status changes from inside the class). I think you are misunderstanding the function of events - an event is defined inside a class and others can subscribe to it by doing

obj.AfterSearch += handler; (where handler is a method according to the signature of AfterSearch). One is able to subscribe to the event from the outside just fine, but it can only be risen from inside the class defining it.

这篇关于在C#中的不同类提高一类的事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆