【发布时间】: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