簡體   English   中英

我可以在運行時為C#中的子類創建(添加)方法重寫(反射/發出嗎?)。

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM