Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using reflection to override virtual method tables in C#

Is there a way to change the virtual methods tables in C#? like change where a virtual method is pointing?

class A
{
    public virtual void B()
    {
        Console.WriteLine("B");
    }
}
class Program
{
    public static void MyB(A a)
    {
        Console.WriteLine("MyB");
    }
    public static void Main(string[] Args)
    {
        A a = new A();
        // Do some reflection voodoo to change the virtual methods table here to make B point to MyB
        a.B(); // Will print MyB
    }
}
like image 967
Dani Avatar asked Feb 25 '23 08:02

Dani


2 Answers

Take a look at LinFu.

On Linfu's author's Blog there's an example of using LinFu.AOP to intercept and change calls even to methods of classes that you don't control directly.

like image 62
Paolo Falabella Avatar answered Feb 26 '23 20:02

Paolo Falabella


You cannot change the types with reflection, you can only reflect over the existing types.

You can, however, build new types using Reflection.Emit and related classes, but short of recompiling your assembly, a.B(); in your example will always call A.B().

like image 34
Lasse V. Karlsen Avatar answered Feb 26 '23 20:02

Lasse V. Karlsen