Automatically call function # 2 when calling function # 1

It should be quick. Is it possible to do something like this:

[Callback(funtionY)]
void functionX()
{
}

void functionY()
{
}

So, when function X is called, function Y is also called automatically? The reason I'm asking for is because I'm going to implement network functions for a small XNA-based game engine, and I want to mention the Synched function to note that when calling the function, it should be called for all clients.

Thanks.

+3
source share
5 answers

Looks like you want Aspect Oriented Programming .

I used PostSharp for this before and it works very well.

+8

, PostSharp, : no; .

+5

Yes, you can just create them as a delegate.

Action foo = functionX;
foo += functionY;

foo(); // both called

UPDATE: John (thank you) noted that the order of treatment is actually defined. I would never rely on this. See Comments.

+4
source

Is there a reason you cannot do this:

void functionX()
{
    functionY();
    // ... etc
}

Based on the description in the question, this is the correct answer. I assume that you have already considered this.

Another possibility is to use the event system to your advantage, something like (uncompiled):

event Action FunctionXCalled;

// somewhere in initialization...
MyCtor()
{
    FunctionXCalled += functionY;
}

void functionY() { }

void functionX()
{
    if(FunctionXCalled != null) FunctionXCalled();
    // ... etc
}
+2
source

What about:

void functionX() {
   functionY();
   // Other implementation stuff
}

void functionY() {

}
0
source

Source: https://habr.com/ru/post/1704438/


All Articles