开发者

C# Trigger a method after another method (defined in a third party dll) is completed

This may fall into the category of method extending, overriding or polymorphism (I'm new to C# and OO so forgive me, I'm still learning :-) ).

I have an app that is utilizing a 3rd party API. Within the API there is a method for right click+select action on a custom control (the control is an image viewer where a user can right click and cycle to another image that exists within the parent group).

In my limited understanding I would think one of these 2 things would need to happen (whether either one can be done or whether either one is a good solution is up in the air!)

  1. I don't want to override the existing method, I just want to append to it somehow.
  2. If there was a way I开发者_C百科 could detect when the specific event was triggered and completed, then call my method. Set up some kind of listener if thats available.

Thanks!!


As you didn't post any reference, I'll try to outline some ways.

  1. if there is an event

    CustomControl cc = yourCustomControl;
    cc.SelectionCompleted += (sender, args) => { YourMethod() };
    

    This is using an anomynous event handler using a lambda.

    Another way would be:

    public class Form1 : Form
    {
       public Form1()
       {
          this.cc.SelectionCompleted += HandlerSelectionCompleted;
       }
       public void HandlerSelectionCompleted(object sender, EventArgs e)
       {
          YourCustomMethod();
       }
    }
    
  2. there is a method to override

    public class YourCustomControl : CustomControl
    {
       public override void Selection()
       {
          base.Selection(); // first call the original method
    
          // now do some custom stuff
       }
    }
    


You can not override that method: that's right, if it's not protected/virtual/abstract whatever, or if you can not derive from that component's class. You can search the component for the events and guess (if there is no any documentation) which event is fired after your desired action. And actually execute the code in that event handle.

There could be other "hacking" tricks, but I personally would avoid to do something like that, if not for personal passion, but focus on reachitecturing my program, in order to fit the requirements and support that component, as much as I can.

Regards.


What you are describing is a tenant of Aspect Oriented Programming AOP. If you want to instrument a 3rd party .NET dll, I would recommend PostSharp http://www.sharpcrafters.com/solutions/logging

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜