how do I subscribe to an event in raised in another assembly

懵懂的女人 提交于 2019-12-11 03:19:06

问题


I have a solution which contains 3 project. One project handles asynchronous communinications. When it has completed it's callback, it raises an event 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.


回答1:


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



回答2:


There's nothing special about events raised in a separate assembly, unless the event itself is declared with the internal access modifier. 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?




回答3:


The event must be declared as public in the class which defines it:

public class Something
{
  public event EventHandler SomethingCompleted;
}

You can then subscribe to it just as to any other event:

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


来源:https://stackoverflow.com/questions/2089575/how-do-i-subscribe-to-an-event-in-raised-in-another-assembly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!