事件触发时的 .NET 注入行为
因此,我有一个方法,我希望每次某个对象时都调用该方法,在本例中,Form
触发了特定事件,在本例中为 FormClosing
。现在我可以做的是创建一个继承 Form
的 MyForm
,然后执行我需要的操作,例如
//Not Sure if this is 100% how you would do this but you get the idea
private void formClosing(Object sender, FormClosingEventArgs e)
{
MyMethod(this);
RaiseEvent MyFormClosing;
}
但是,如果我不想这样做怎么办多于。是否有一些框架或模式基本上可以让我将想要的行为注入到代码中?
如果这还不够清楚,我可以解释更多。
So I have an Method that I want to be called every time a Certain Object, in this case a Form
has a specific event fired, in this case FormClosing
. Now what I could do is create a MyForm
that inherits Form
and then does what I need it to something like
//Not Sure if this is 100% how you would do this but you get the idea
private void formClosing(Object sender, FormClosingEventArgs e)
{
MyMethod(this);
RaiseEvent MyFormClosing;
}
However, what if I don't want to have to do the above. Is there some framework or pattern that would basically let me inject the behavior that want into code?
If this isn't clear enough I can explain more.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
向 MyForm 类添加一个可以设置为 true 或 false 的属性是否足以告诉它不要调用该方法?就我个人而言,我会重写 Closing 方法而不是订阅该事件。
如果 MyMethod 位于表单外部,您可以使用委托(也许命名也更好),
但实际上由于它是一个表单,如果您想调用外部方法,最好订阅 Forms Closing 事件。
** OP 编辑 **
这足够接近我想要去的地方,即创建一个继承自
Form
的部分类,并重写那里的事件来执行我想要的操作。Would adding a property that you can set to true or false to the MyForm class be enough to tell it not to call the method? Personally I would override the Closing method rather than subscribe to the event.
If MyMethod is external to the form you can instead use delegates (maybe better naming as well)
but really since it is a form, if you wanted to call an external method it would be better to subscribe to the Forms Closing event.
** OP Edit **
This was close enough to get me to where I wanted to go which was creating a partial class that inherited from
Form
and overriding the events there to do what I wanted.