mercredi 15 avril 2020

adding event to another class after completion of a method

Suppose I have two classes - one that is provided to me (but suppose I am not allowed to change it as it is maintained by someone else), and one that I control and can change.

// Class A is provided to me by someone else, and suppose I can't modify it
public class A
{
   public A()
   {
    ...
   }

   public void DoSomethingInA()
   {
    ...
   }
}

// Class B is what I control
public class B
{
   public A MyClassAInstance;

   public B(A myClassAInstance)
   {
     MyClassAInstance = myClassAInstance;

     // *** HERE IS WHERE I NEED HELP
     // NEED TO WRITE AN EVENT / EVENT HANDLER, WITH / WITHOUT REFLECTION
     // THAT RUNS DoSomethingInB WHENEVER MyClassAInstance's DoSomethingInA
     // METHOD IS CALLED (AND COMPLETED)
   }

   public void DoSomethingInB()
   {
    ...
   }

}

How can I define a Event / EventHandler in class B that kicks off its DoSomethingInB method whenever the class A instance MyClassAInstance's method DoSomethingInA is called (and completed).

I tried lot of options, but none seem to work.

For instance, I tried:

public class B
{
   public A MyClassAInstance;

   public B(A myClassAInstance)
   {
     MyClassAInstance = myClassAInstance;

     var eventInfo = GetType().GetEvent("MyEvent");
     var methodInfo = myClassAInstance.GetType().GetMethod("DoSomethingInA");
     Delegate handler = Delegate.CreateDelegate(eventInfo.EventHandlerType, myClassAInstance, methodInfo);
     eventInfo.AddEventHandler(this, handler);
     MyEvent += DoSomethingInB;

   }

   public event EventHandler MyEvent;

   public void DoSomethingInB()
   {
    ...
   }

}

But this doesn't work.

Any suggestions or help would be greatly appreciated.





Aucun commentaire:

Enregistrer un commentaire