jeudi 6 décembre 2018

Can I create (add) a method override at runtime for a child class (reflection/emit?) in C#

I have a child class that does not override one of it's parent's base methods. I want to create that override at runtime. Can I do that? I know it's possible to modify a method that already exists, but this is slightly different.

Suppose I have:

class MyBaseClass
{
  public bool testMethod() {
    return false;
  }
}

class MyChildClass : MyBaseClass
{
}

...
MyBaseClass p=new MyBaseClas();
MyChildClass child=new MyChildClass();

p.testMethod();      // should always return false
child.testMethod();  // returns false

....  // Do Magic?

// Make child.testMethod(); return true

If MyChildClass had created an override of testMethod(), I could use Reflection;

// If
class MyChildClass : MyBaseClass
{
  public override bool testMethod() {
    return false;
  }
}
// then I could have
MethodInfo m = typeof(MyChildClass).GetMethod("testMethod");
// and then do reflection stuff to change it

But m is null.

Can I make it so whenever a MyChildClass instance calls testMethod(), it returns true?





Aucun commentaire:

Enregistrer un commentaire