提问者:小点点

如何在C#中为接口提供新的行为?


我想修改实现特定接口的类实例的行为。修改由修改器对象执行。最终,原始类实例仍应保留其所有其他行为。设置如下:

接口和实现类如下所示:

interface IFuncA
{
  double DoSomethingA();
}
interface IFuncB
{
  int DoSomethingB(string str);
}

class ImplementsAB : IFuncA, IFuncB
{
  void DoSomethingA() => 3.14;
  int DoSomethingB(string str) => str.Length;
}

有一些修改器类根据下面的psuedoCode工作。这是我想不明白的部分。

// Unknown how to make this work.
class ModifiesFuncB
{
  int Multiplier;
  int ModifiedDoSomethingB(string str) => Multiplier * str.Length;

  ModifiesFuncB(int multiplier)
  {
    Multiplier = multiplier;
  }

  IFuncB Modify(IFuncB funcB)
  {
    // This is pseudo-code.
    funcB.DoSomethingB = ModifiedDoSomethingB;
  }
}

下面是一些示例代码,使用修饰符修改实现IFUNCB接口的对象上的行为。

ImplementsAB myObj = new ImplementsAB();
ModifiesFuncB modifier = new ModifiesFuncB(2);

Console.WriteLine(myObj.DoSomethingA());        // Outputs 3.14
Console.WriteLine(myObj.DoSomethingB("hello")); // Outputs 5

myObj = modifier.Modify(myObj);

Console.WriteLine(myObj.DoSomethingA());        // Outputs 3.14
Console.WriteLine(myObj.DoSomethingB("hello")); // Outputs 10

是否有解决方案、软件设计模式或通用方法来完成此操作?这可能是一个完全错误的方式,但示范我应该做的将是一个很大的帮助。提前道谢!


共1个答案

匿名用户

您可能正在寻找

Decorator模式-“动态地将附加的resposities附加到一个对象。Decorator提供了一个灵活的替代子类化来扩展功能。”(Gamma,Erich,等人,“可重用的面向对象软件的元素”,《设计模式》,马萨诸塞州:Addison-Wesley Publishing Company(1995))。