开发者

.NET Inject Behavior on Event Firing

开发者 https://www.devze.com 2023-02-25 14:14 出处:网络
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

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 f开发者_StackOverflow中文版ramework or pattern that would basically let me inject the behavior that want into code?

If this isn't clear enough I can explain more.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消