从 C# 中的不同类引发类的事件 [英] Raise an event of a class from a different class in C#

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

问题描述

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

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

public event EventHandler AfterSearch;

我有另一个类,EventRaiser.cs.我如何从这个类中引发(而不是处理)上述事件?

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

引发的事件将依次调用 EventContainer 类中的事件处理程序.像这样(这显然不正确):

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);

推荐答案

这是不可能的,Events 只能从类内部引发.如果你能做到这一点,它就会违背事件的目的(能够从班级内部提升状态变化).我认为您误解了事件的功能 - 在类中定义了一个事件,其他人可以通过这样做来订阅它

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;(其中 handler 是根据 AfterSearch 签名的方法).一个可以从外部订阅事件就好了,但它只能从定义它的类内部上升.

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天全站免登陆