【问题标题】:C# - require an interface on a base class but only the implementations in derived classesC# - 需要基类上的接口,但只需要派生类中的实现
【发布时间】:2011-05-08 02:57:46
【问题描述】:

我正在尝试创建一个基类,为从它派生的许多类提供大量可重用的功能。通过提供这个功能,我还想要求派生类也实现某些方法,即实现一个接口。但是,我不想明确告诉派生类他们需要实现接口,我希望在基类中定义该要求。所以基本上,一旦一个类从基类继承,它就会获得功能,但也需要自己实现其他方法。这就是我想要的,老实说,我不确定这是否可能:

public interface IExtraStuff {
  bool test();
}

public class BaseControl : System.Web.UI.UserControl, IExtraStuff {

  public bool foo(){
    return true;
  }

  // I don't actually want to implement the test() method in this
  // class but I want any class that derives from this to implement it.

}

MyUserControl1 : BaseControl {

  // this.foo() can be used here

  // according to IExtraStuff from the BaseControl, I need to implement test() here

}

基本上我不想将MyUserControl1 定义为:

MyUserControl1 : BaseControl, IExtraStuff

我希望它在继承 BaseControl 的额外功能后自动需要接口。

如果这不可能,请告诉我,这很好。我只是对此知之甚少。正如我目前编写的那样,它可以编译,我觉得我应该得到一个编译错误,因为test() 没有在MyUserControl1 中定义。

更新

我已经将我的基类修改为抽象的(我在发布到 SO 之前已经这样做了)但我实际上可以在不实现抽象方法的情况下构建项目,这就是我开始问这个问题的原因。下面的代码是为我构建的,我对此感到困惑:

public interface IExtraStuff {
  bool test();
}

public abstract class BaseControl : System.Web.UI.UserControl, IExtraStuff {

  public abstract bool test();

  public bool foo(){
    return true;
  }

}

MyUserControl1 : BaseControl {

  // this.foo() can be used here

  // I can build without implementing test() here!

}

更新 2:问题已解决

事实证明,我的解决方案构建设置存在问题,除非我从基础(现在)实现抽象方法,否则项目不会构建。这是我在 Visual Studio 中的错误,而不是类体系结构中的错误。感谢大家的帮助!

【问题讨论】:

  • 我假设 MyUserControl1 : BaseControl 是一个公共类?因为发布的内容不应该编译?
  • 是的,我想简单地输入一个样本,但错过了那个关键字。总体错误出现在我在 Visual Studio 中的项目设置和我的构建中。我的错,不是架构的问题。

标签: c# class inheritance interface abstraction


【解决方案1】:

使用抽象方法?

public abstract class BaseControl : System.Web.UI.UserControl, IExtraStuff { 

  public bool foo(){ 
    return true; 
  } 

  public abstract bool test();  
} 

查看更多信息: http://msdn.microsoft.com/en-us/library/aa664435(VS.71).aspx

编辑 添加派生类实现。

public class MyCustomControl : BaseControl { 

  public override bool test()
  {
    //Add Code...
  }  
} 

【讨论】:

  • 您还必须将类标记为抽象类,否则会出现编译错误
  • 我实际上尝试过这个,并且在我的派生类中我不需要定义test(),当我在代码块中输入test() 时,它会从基类中获取它,就好像它有一个定义的身体,它没有。 现在正在阅读那篇文章...
  • @Mark 如果您已将类正确标记为抽象类(不确定 Jeff 的编辑时间是什么),那么您将收到构建错误,告诉您您的具体类需要实现抽象方法测试()
  • 再次感谢马特,在添加评论之前只是添加了派生类的 impl :D
  • @Matt,我确实将该类标记为抽象类,但我没有在派生类中为test() 定义实现,我可以构建项目!这就是促使我提出这个问题的原因,我真的很困惑它为什么会构建!在我实现该方法之前,我一直期待编译时错误。
【解决方案2】:

这就是抽象类和方法的用途

public abstract class BaseControl : IExtraStuff
{
   public abstract bool test();
}

注意,类也需要标记为抽象类

【讨论】:

    【解决方案3】:

    如果将 BaseControl 设为抽象类,则可以省略接口成员,因此强制在子类中实现。

    【讨论】:

    • 您不能省略接口成员,但可以通过将它们标记为抽象来使它们不实现。这不完全一样。
    猜你喜欢
    • 2013-11-23
    • 1970-01-01
    • 2011-02-11
    • 1970-01-01
    • 2013-06-02
    • 1970-01-01
    • 2021-05-23
    • 2010-09-22
    • 2017-07-18
    相关资源
    最近更新 更多