“在运行时覆盖方法”C#

时间:2010-11-04 10:48:51

标签: c# runtime override

我想在自定义dll中覆盖ClassA的方法Print。

public ClassA
{
    public void Print( string arg1, string arg2, string arg3, string arg4 )
    {
    }
}

这在C#中是否可行?

4 个答案:

答案 0 :(得分:1)

我相信微软研究院的Moles也做了类似的事情。它们有一个允许你覆盖例如工作的系统。 DateTime.Now,强制它返回特定的日期/时间。

有关详细信息,请查看http://research.microsoft.com/en-us/projects/pex/default.aspx

答案 1 :(得分:1)

这与你提出的问题不太一样,但它也会产生类似的效果......

为什么不为您的操作定义接口。 ClassA实现了接口。您的自定义策略也实现了界面。 ClassA在启动时(在实例化ClassA时)内部创建接口的“默认”实现,但也具有允许设置接口的属性。该接口甚至可以允许自定义策略指定它实际实现的接口的哪些成员:

interface IStrategy
{
  void Operation1(int x, int y);
  void Operation2(string a, string b);
}

class ClassA : IStrategy
{
  private IStrategy builtInStrategy = new BuiltInStrategy();

  public IStrategy CustomStrategy { get; set; }

  void Operation1(int x, int y);
  {
    if (CustomStrategy != null)
    {
      CustomStrategy.Operation1(x, y);
    }
    else
    {
      builtInStrategy.Operation1(x, y);
    }
  }

  void Operation2(string a, string b)
  {
    if (CustomStrategy != null)
    {
      CustomStrategy.Operation2(a, b);
    }
    else
    {
      builtInStrategy.Operation2(a, b);
    }
  }
}

您可以指定IStrategy接口的一部分,以便自定义策略指示它不会“覆盖”特定操作。也许它可以返回bool而不是空格,或者如果自定义策略没有覆盖操作,每个操作可能都有一个out bool参数设置为false。

根据可以覆盖的操作数量,您甚至可以考虑将每个操作放在自己的界面上。如果在没有实现其他操作的情况下实现一个操作是不合理的,则可以将操作分组到接口中。

interface IOperation1
{
  void Operation1(int x, int y);
}

interface IOperation2
{
  void Operation2(string a, string b);
}

interface IMath
{
  int Add(int i, int j);
  int Subtract(int i, int j);
  int Multiply(int i, int j);
  int Divide(int i, int j);
}

interface IStrategy
{
  //What operations should the Strategy have?
}

class ClassA : IOperation1, IOperation2, IMath
{
  public IStrategy CustomStrategy { get; set; }

  public void Operation1(int x, int y)
  {
    IOperation1 op1 = CustomStrategy as IOperation1;
    if (op1 != null)
    {
      op1.Operation1(x, y);
    }
    else
    {
      //Do ClassA's Operation1 logic here
    }
  }

  public void Operation2(string a, string b)
  {
    IOperation2 op2 = CustomStrategy as IOperation2;
    if (op2 != null)
    {
      op2.Operation2(a, b);
    }
    else
    {
      //Do ClassA's Operation2 logic here
    }
  }

  //
  // And so on ...
  //
}

答案 2 :(得分:0)

您的第一个问题:该方法未标记为virtual。你不能override非虚方法。

至于问题,这完全取决于ClassA如何实例化和使用。例如,您可以在运行时创建派生类型,如果您可以控制它的实例化和使用。

答案 3 :(得分:0)

这是不可能的,因为我无法扩展ClassA,因为它在随应用程序提供的Core dll中

相关问题