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?
To modify the behavior of a derived class at runtime you should build that in as a feature of the class:
class MyBaseClass
{
public virtual bool TestMethod() => false; // MUST BE VIRTUAL
}
class MyChildClass : MyBaseClass
{
public MyChildClass()
{
implementation = () => base.TestMethod();
}
private Func<bool> implementation = null;
public override bool TestMethod() => this.implementation();
public void SetImplementation(Func<bool> f) => this.implementation = f;
}
And now you can make a new MyChildClass
and call SetImplementation(()=>true);
to change the behaviour of the class.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.