一千萬個為什麽

搜索

C#在運行時更改類方法

我需要擴展實例的行為,但我無法訪問該實例的原始源代碼。例如:

/* I don't have the source code for this class, only the runtime instance */
Class AB
{
  public void execute();
}

在我的代碼中,我會截取每個執行調用,計算一些sutff,然後調用原始執行,類似於

/* This is how I would like to modify the method invokation */
SomeType m_OrgExecute;

{
    AB a = new AB();
    m_OrgExecute = GetByReflection( a.execute );
    a.execute = MyExecute;
}

void MyExecute()
{
    System.Console.Writeln( "In MyExecute" );
    m_OrgExecute();
}

那可能嗎?

有沒有人有這個問題的解決方案?

最佳答案

看起來您需要裝飾器模式

class AB
{
   public void execute() {...}
}

class FlaviosABDecorator : AB
{
   AB decoratoredAB;

   public FlaviosABDecorator (AB decorated)
   {
       this.decoratedAB = decorated;
   }

   public void execute()
   {
       FlaviosExecute();  //execute your code first...
       decoratedAB.execute();
   }

   void FlaviosExecute() {...}
}

然後,您必須修改使用 AB 對象的代碼。

//original code
//AB someAB = new AB();

//new code
AB originalAB = new AB();
AB someAB = new FlaviosABDecorotor(originalAB);

/* now the following code "just works" but adds your method call */

轉載註明原文: C#在運行時更改類方法