简体   繁体   English

我如何订阅另一个程序集中引发的事件

[英]how do I subscribe to an event in raised in another assembly

I have a solution which contains 3 project. 我有一个包含3个项目的解决方案。 One project handles asynchronous communinications. 一个项目处理异步通信。 When it has completed it's callback, it raises an event SomethingCompleted. 当它完成它的回调时,它会引发一个事件SomethingCompleted。 How do I subscribe to this event from another project in the same solution? 如何在同一解决方案中从另一个项目订阅此事件?

I have the event handlers built in the receiving project but it does not see the event in the sending project. 我在接收项目中构建了事件处理程序,但它没有在发送项目中看到事件。

There's nothing special about events raised in a separate assembly, unless the event itself is declared with the internal access modifier. 除非事件本身是使用internal访问修饰符声明的,否则在单独的程序集中引发的事件没有什么特别之处。 Check that it's public. 检查它是否公开。

To give an example of what I mean, I'm sure you don't think twice about subscribing to Button.Click - but Button is in a different assembly, isn't it? 举一个我的意思的例子,我敢肯定你不会想到订阅Button.Click - 但是Button在一个不同的程序集中,不是吗?

The event must be declared as public in the class which defines it: 必须在定义它的类中将事件声明为public:

public class Something
{
  public event EventHandler SomethingCompleted;
}

You can then subscribe to it just as to any other event: 然后,您可以像任何其他事件一样订阅它:

Something s = ...;
s.SomethingCompleted += SomeEventHandler;

You need to have a reference to the class raising the event to register an event handler. 您需要引用引发事件的类来注册事件处理程序。

Once you have that, it's done like registering any other event handler: 一旦你拥有了它,就像注册任何其他事件处理程序一样:

foo.SomethingCompleted += (sender, e) => this.DoSomething();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM