[英]Can I create (add) a method override at runtime for a child class (reflection/emit?) in C#
我有一个子类,它不会覆盖其父类的基本方法之一。 我想在运行时创建该替代。 我可以那样做吗? 我知道可以修改一个已经存在的方法,但这有点不同。
假设我有:
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
如果MyChildClass创建了testMethod()的覆盖,则可以使用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
但是m为空。
每当MyChildClass实例调用testMethod()时,都可以返回true吗?
要在运行时修改派生类的行为,您应该将其内置为类的功能:
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;
}
现在您可以创建一个新的MyChildClass
并调用SetImplementation(()=>true);
改变班级的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.