繁体   English   中英

C#-需要基类上的接口,但仅派生类中的实现

[英]C# - require an interface on a base class but only the implementations in derived classes

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

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的额外功能后自动需要该接口。

如果这不可能,请告诉我,这很好。 我只是不够了解。 正如我目前编写的那样,它可以编译,并且由于没有在MyUserControl1定义test() ,我觉得应该得到一个编译错误。

UPDATE

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

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中的错误,不是类体系结构中的错误。 谢谢各位的帮助!

使用抽象方法?

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

  public bool foo(){ 
    return true; 
  } 

  public abstract bool test();  
} 

请参阅更多信息: http : //msdn.microsoft.com/zh-cn/library/aa664435(VS.71).aspx

编辑添加派生类隐含。

public class MyCustomControl : BaseControl { 

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM