你如何跨课程触发事件?

时间:2010-02-22 20:49:55

标签: class delegates events event-handling

我正在编写一个将被其他应用程序使用的类库。我是用C#.NET编写的。我遇到了跨类触发事件的问题。这是我需要做的......

public class ClassLibrary
{
    public event EventHandler DeviceAttached;

    public ClassLibrary()
    {
        // do some stuff
        OtherClass.Start();
    }
}

public class OtherClass : Form
{
    public Start()
    {
        // do things here to initialize receiving messages
    }

    protected override void WndProc (ref message m)
    {
       if (....)
       {
          // THIS IS WHERE I WANT TO TRIGGER THE DEVICE ATTACHED EVENT IN ClassLibrary
          // I can't seem to access the eventhandler here to trigger it.
          // How do I do it?

       }
       base.WndProc(ref m);
    }

}

然后在使用类库的应用程序中,我将执行此操作...

public class ClientApplication
{
    void main()
    {
       ClassLibrary myCL = new ClassLibrary();
       myCL.DeviceAttached += new EventHandler(myCl_deviceAttached);
    }

    void myCl_deviceAttached(object sender, EventArgs e)
    {
         //do stuff...
    }
}

1 个答案:

答案 0 :(得分:1)

可能最简单的选择是向ClassLibrary添加一个引发事件的方法......即

internal void RaiseDeviceAttached(object sender, EventArgs e)
{
  if (DeviceAttached != null) DeviceAttached(sender, e);
}

然后,在OtherClass中,只需调用ClassLibrary的方法。

另一种选择是沿着反射路线向下触发事件。