Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Changing class method at run-time [duplicate]

Tags:

c#

.net

runtime

I need to extend the behavior of an instance, but I don't have access to the original source code of that instance. For example:

/* I don't have the source code for this class, only the runtime instance */
Class AB
{
  public void execute();
}

in my code I would to intercept every call to execute, compute some sutff and then call the original execute, something like

/* This is how I would like to modify the method invokation */
SomeType m_OrgExecute;

{
    AB a = new AB();
    m_OrgExecute = GetByReflection( a.execute );
    a.execute = MyExecute;
}

void MyExecute()
{
    System.Console.Writeln( "In MyExecute" );
    m_OrgExecute();
}

Is that possible?

Does anyone have a solution for this problem?

like image 662
Flavio Avatar asked Dec 12 '22 22:12

Flavio


2 Answers

It looks like you want the Decorator pattern.

class AB
{
   public void execute() {...}
}

class FlaviosABDecorator : AB
{
   AB decoratoredAB;

   public FlaviosABDecorator (AB decorated)
   {
       this.decoratedAB = decorated;
   }

   public void execute()
   {
       FlaviosExecute();  //execute your code first...
       decoratedAB.execute();
   }

   void FlaviosExecute() {...}
}

You'd then have to modify the code where the AB object is used.

//original code
//AB someAB = new AB();

//new code
AB originalAB = new AB();
AB someAB = new FlaviosABDecorotor(originalAB);

/* now the following code "just works" but adds your method call */
like image 103
Austin Salonen Avatar answered Dec 15 '22 12:12

Austin Salonen


There is no way to do this directly via reflection, etc.

In order to have your own code injected like this, you'll need to create a modified version of their assembly, and use some form of code injection. You cannot just "change a method" of an arbitrary assembly at runtime.

like image 39
Reed Copsey Avatar answered Dec 15 '22 13:12

Reed Copsey