【问题标题】:C# Overriding abstract methods (include input parameters)C# 重写抽象方法(包括输入参数)
【发布时间】:2011-12-27 01:19:40
【问题描述】:

在 C# 中可以做这样的事情

public absctract class ImportBase()
{
   public abstract void CreateDocument();
}
public class UsingOne : ImportBase
{
   public override bool CreateDocument(string name)
   {
      return null;
   }
}

我想要一些基类,它只有一些方法,但在派生类中我需要更改输入参数和方法内部。

【问题讨论】:

    标签: c# class interface abstract-class


    【解决方案1】:

    您没有覆盖该方法。拥有一个抽象(或虚拟)方法的意义在于,给定任何ImportBase,我应该能够调用

    importBase.CreateDocument();
    

    显然不是UsingOne 的情况,因为它需要更多信息。所以你真的想把你的调用者绑定到UsingOne,而不仅仅是ImportBase——此时你已经失去了多态性的好处。

    要覆盖一个方法,实现必须具有相同的签名,基本上。

    【讨论】:

    • 我明白了。想办法只规定方法,派生类说明方法需要什么,返回什么
    【解决方案2】:

    不。派生类上的签名必须相同。我建议使用构建器模式。

    http://en.wikipedia.org/wiki/Builder_pattern

    【讨论】:

      【解决方案3】:

      您可能希望尽量减少派生类上的重复代码。基本上不可能覆盖不同的签名,但您当然可以重构代码,将可能的重复代码保留在基类中并在派生类中使用。

      public absctract class ImportBase()
      {
         //Making this protected here
         protected virtual void CreateDocument() 
         {
            //Your CreateDocument code
         };
      }
      
      public class UsingOne : ImportBase
      {
         private override void CreateDocument()
         {
            // Override this if you have different CreateDocument for your different
            // for different derived class.
         }
         public bool CreateDocument(string name)
         {
            // Do whatever you need to do with name parameter.
            base.CreateDocument();
            // Do whatever you need to do with name parameter.
            return true; // return false;
         }
      }
      

      您可以创建UsingOne 的实例并调用CreateDocument(string name)

      【讨论】:

      • 覆盖必须受到保护而不是私有。
      猜你喜欢
      • 1970-01-01
      • 2013-10-24
      • 1970-01-01
      • 2014-08-28
      • 1970-01-01
      • 2014-05-30
      • 2013-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多