事件触发时的 .NET 注入行为

发布于 2024-11-01 20:22:32 字数 461 浏览 0 评论 0原文

因此,我有一个方法,我希望每次某个对象时都调用该方法,在本例中,Form 触发了特定事件,在本例中为 FormClosing。现在我可以做的是创建一个继承 FormMyForm ,然后执行我需要的操作,例如

//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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

快乐很简单 2024-11-08 20:22:32

向 MyForm 类添加一个可以设置为 true 或 false 的属性是否足以告诉它不要调用该方法?就我个人而言,我会重写 Closing 方法而不是订阅该事件。

protected override void OnFormClosing(FormClosingEventArgs e)
{
   if(CallMyMethod)
   {
       MyMethod(this);
   }

   base.OnFormClosing(e);
}

如果 MyMethod 位于表单外部,您可以使用委托(也许命名也更好),

public Action<Form> MyMethod { get; set; }
protected override void OnFormClosing(FormClosingEventArgs e)
{
   if(MyMethod != null)
   {
       MyMethod(this);
   }

   base.OnFormClosing(e);
}

但实际上由于它是一个表单,如果您想调用外部方法,最好订阅 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.

protected override void OnFormClosing(FormClosingEventArgs e)
{
   if(CallMyMethod)
   {
       MyMethod(this);
   }

   base.OnFormClosing(e);
}

If MyMethod is external to the form you can instead use delegates (maybe better naming as well)

public Action<Form> MyMethod { get; set; }
protected override void OnFormClosing(FormClosingEventArgs e)
{
   if(MyMethod != null)
   {
       MyMethod(this);
   }

   base.OnFormClosing(e);
}

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文