在我的PluginManager代码中,事件 PluginEvent 被触发 添加了一个插件。但是我希望在测试类中触发事件。 不知怎的,我无法解决这个问题。该事件仅在 PluginManager类中触发。我读了一些文章如何创建事件等等,但我更加困惑
PluginManager类
public class PluginEventArgs
{
public PluginEventArgs(string s) { Text = s; }
public String Text { get; private set; } // readonly
}
public class PluginManager
{
// Declare the delegate (if using non-generic pattern).
public delegate void PluginEventHandler(object sender, PluginEventArgs e);
// Declare the event.
public event PluginEventHandler PluginEvent;
protected virtual void RaiseSampleEvent(string message)
{
if (PluginEvent != null)
PluginEvent(this, new PluginEventArgs(message));
}
public PluginManager()
{
PluginEvent += PluginManager_PluginEvent;
SomeMethod();
}
void PluginManager_PluginEvent(object sender, PluginEventArgs e)
{
//This event gets triggered =)
}
public void SomeMethod()
{
//Code
RaiseSampleEvent("Name of the Plugin");
//Code
}
}
我的测试类:
class test
{
public test()
{
PluginManager pluginMg = new PluginManager();
pluginMg.PluginEvent += pluginMg_PluginEvent;
}
//I want this event to get triggered when a new plugin has been found
void pluginMg_PluginEvent(object sender, PluginEventArgs e)
{
MessageBox.Show(e.Text);
}
}
如何设法在测试类中触发事件? 谢谢你的任何建议!
答案 0 :(得分:3)
除了一个合乎逻辑的错误之外,你实际上是在做正确的事。
在测试类中,您使用构造函数创建PluginManager。 PluginManager的构造函数首先订阅该事件然后引发它。
之后您正在订阅该活动。
简单问题是,当您举起活动时,您的测试类尚未订阅。当你再次举起那个活动时,一切都应该没问题。
另一件事是我会使用通用的EventHandler类而不是创建自己的委托。这使您的代码更清晰,每个人都知道这是一个乍看之下的事件。
只需从EventArgs继承PlugInEventArgs,然后使用EventHandler。
答案 1 :(得分:1)
在PluginManager类中,您不应该订阅自己的事件PluginEvent,您应该订阅外部事件或者只是引发PluginEvent。 让我举个例子:
public class PluginEventArgs
{
public PluginEventArgs(string s) { Text = s; }
public String Text { get; private set; } // readonly
}
public class OtherClass
{
public event PluginEventHandler PluginEvent;
private void RaiseEvent()
{
if (null != PluginEvent)
PluginEvent(this, new PluginEventArgs("some message"));
}
}
public delegate void PluginEventHandler(object sender, PluginEventArgs e);
public class PluginManager
{
public event PluginEventHandler PluginEvent;
private OtherClass otherClass;
protected virtual void RaiseSampleEvent(string message)
{
if (PluginEvent != null)
PluginEvent(this, new PluginEventArgs(message));
}
public PluginManager(OtherClass otherClass)
{
this.otherClass = otherClass;
this.otherClass.PluginEvent += otherClass_PluginEvent;
SomeMethod();
}
void otherClass_PluginEvent(object sender, PluginEventArgs e)
{
if (PluginEvent != null)
PluginEvent(sender, e); // this way the original sender and args are transferred.
}
public void SomeMethod()
{
//Code
RaiseSampleEvent("Name of the Plugin");
//Code
}
}
class test
{
public test()
{
OtherClass otherClass = new OtherClass();
PluginManager pluginMg = new PluginManager(otherClass);
pluginMg.PluginEvent += pluginMg_PluginEvent;
}
//I want this event to get triggered when a new plugin has been found
void pluginMg_PluginEvent(object sender, PluginEventArgs e)
{
MessageBox.Show(e.Text);
}
}