PIC*_*ain 5 c# delegates class 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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后在使用类库的应用程序中,我将执行此操作...
public class ClientApplication
{
void main()
{
ClassLibrary myCL = new ClassLibrary();
myCL.DeviceAttached += new EventHandler(myCl_deviceAttached);
}
void myCl_deviceAttached(object sender, EventArgs e)
{
//do stuff...
}
}
Run Code Online (Sandbox Code Playgroud)
你不能做这个.事件只能从声明事件的类中引发.
通常,您需要在类上添加一个方法来引发事件,并调用该方法:
public class ClassLibrary
{
public event EventHandler DeviceAttached;
public void NotifyDeviceAttached()
{
// Do processing and raise event
}
Run Code Online (Sandbox Code Playgroud)
然后,在你的其他代码中,你只需要打电话 myCL.NotifyDeviceAttached();
我认为你应该改变对事件如何运作的看法。OtherClass 应该“拥有”该事件并触发它。ClassLibrary 或 ClientApplication(无论您选择哪个)通过“订阅”事件来“侦听”该事件,并在该事件发生时执行特定操作。
如何实现:
public class ClassLibrary
{
public OtherClass myOtherCl;
public ClassLibrary()
{
myOtherCl= new OtherClass();
myOtherCl.Start();
}
}
Run Code Online (Sandbox Code Playgroud)
在逻辑上发生事件、检测到事件的类中触发事件。
public class OtherClass : Form
{
public event EventHandler DeviceAttached;
public Start()
{
// do things here to initialize receiving messages
}
protected override void WndProc (ref message m)
{
if (....)
{
OnDeviceAttach();
}
base.WndProc(ref m);
}
public void OnDeviceAttach()
{
if (DeviceAttached != null)
DeviceAttached ();
}
}
Run Code Online (Sandbox Code Playgroud)
最后,任何需要监听事件的人都需要访问持有该事件的类的实例,这就是为什么 myOtherCl 在本例中被公开。
public class ClientApplication
{
void main()
{
ClassLibrary myCL = new ClassLibrary();
myCL.myOtherCl.DeviceAttached += new EventHandler(myCl_deviceAttached);
}
void myCl_deviceAttached(object sender, EventArgs e)
{
//do stuff...
}
}
Run Code Online (Sandbox Code Playgroud)