Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hook to function without delegates (Reflection)

Tags:

Is there a way I could use reflection to hook one function to another without using delegates?

class A
{
    void Foo()
    {
    }
}

class B
{
    void Main()
    {
        A a = new A();
        a.GetType().GetMethod("Foo").AddHook(a, Func); //I want something like this
        a.Foo();
        //Func gets called
    }

    void Func()
    {
    }
}

Is there a way to call Func after Foo was called without using events, delegates or just calling Func from inside Foo?

I need this so my game's UI controller can get updated.

The way I see most people dealing with this is by adding a bunch of events to A and subscribing B to those. Like this

class A
{
‎    public delegate void UICallback();
‎    public event UICallback onFoo;
    void Foo()
    {
    ‎    onFoo.Invoke();
    }
}

class B
{
    void Main()
    {
        A a = new A();
        ‎a.onFoo += Func;
        a.Foo();
    }

    void Func()
    {
    }
}

The problem I find with this approach is that I'd need to add a bunch of events like these (probably more than 5 or even 10) to many classes and then remember to invoke those at the end of a function to update UI (invoke onBattleStarted at the end of StartBattle(), for example). This, in addition to increasing the size of my classes with big blocks of event declarations making it ugly to read, makes it a harder maintain.

EDIT I think no one really understands what I'm looking for... I'd like a way to hook Func to Foo without making any changes to Foo, i.e. without Foo knowing this callback exists. Using an action won't help since I'd need specify on Foo's parameters that it should call Func

Thank you for your help!

like image 760
ItsaMeTuni Avatar asked Jan 16 '18 18:01

ItsaMeTuni


1 Answers

You Can call Action at the end of Func().

Class A
{
   void Foo()
   {
   }
}

Class B
{
   void Main()
   {
    A a = new A();
    Func( () => {a.Foo();});
   }

   void Func(Action onFinish)
   {
    //Enter your code here
    onFinish();
   }
like image 173
Bilal Sehwail Avatar answered Sep 20 '22 13:09

Bilal Sehwail