我有一个关于如何在我的C#程序中正确使用接口和抽象类的问题。我有许多独立的“模块”(BeatsPerMinuteMeasurement,MouseRecorder,ClipboardHistory等)。他们都至少有一个面板(UserControl)和一个“逻辑”(普通类)。首先,没有继承。但是,现在我重写这样的:( - >)指继承:使用独立“模块”的接口和基类
- SomeLogic - > BaseLogic - > IBaseLogic
- SomePanel - > BasePanel - >用户控件,IBasePanel
的问题:这是一个好办法吗?这里是我的面板的代码(这是不奇怪的,因为继承错误的工作):
interface IBasePanel {
void RegisterEvents();
void Close();
}
abstract class BasePanel : UserControl, IBasePanel {
public BasePanel() {
InitializeComponent();
RegisterEvents(); //Compiler error, compiler cant find it
}
public abstract void InitializeComponent();
}
class MouseKeyRecord_Panel : BasePanel {
//GUI variables (buttons/labels etc.)
public MouseKeyRecord_Panel() {
}
protected override void RegisterEvents() {
//Register EventHandler for buttons etc.
}
protected override void InitializeComponent() {
//Visual Studio auto generated GUI
}
public override void Close() {
//Closing Threads etc.
}
}
编辑1 解决。 我删除了界面,现在它正在工作。我想我以错误的方式使用了接口。我仍然不知道何时使用抽象类以及何时使用接口。因为,因为编译器规定的RegisterEvents()
和Close()
所需的实现并没有在你的BaseClass
实施出现时
如果你没有继承,你为什么要开始做呢?目前不工作吗?无论你试图达到什么样的目标,都可以用组合而不是继承来解决。 –
好吧,它的工作,但我想重新设计它们使其“更好”。他们都有一些共同的东西。他们都有一个Close,InitializeComponent和RegisterEvents方法。我通过这种方式了解到:如果您看到类具有相同的方法,请使用基类,以便每个需要该方法的类都可以继承它。 – Need