我有一些具有.NET控件的类:
Class MyTextBox : Inherits MyControl
Control As TextBox
我想使用继承而不是包含.NET控件的变量:
Class MyTextBox : Inherits TextBox
由于.NET不支持多继承,有没有办法从MyControl类继承并拥有.NET TextBox的所有实现?
Class MyControl : Inherits Control
Class MyTextBox : Inherits MyControl
(all methods, property, events of the TextBox class)
所以我可以拥有TextBoxes,ComboBoxes以及我的子类中的所有属性/操作以及从子类继承的MyControl类的个人和通用atts / ops。
答案 0 :(得分:3)
正如您所说,.NET(以及大多数现代语言和OOP环境)不支持多继承 - 这是一个很好的设计决策 - 。
不是解决方法,但实际的解决方案是包装。
如果您希望自己的控件为MyControl
,还有TextBox
,则可以通过其他方式获得此类关系: interfaces 。
您的专用TextBox
应继承.NET内置TextBox
控件类并实现IMyControl
接口。
SpecializedTextBox
必须实现的功能可以在单独的类中实现,并在IMyControl
SpecializedTextBox
的{{1}}实现中使用其成员。
我将在C#中写下一个示例,但是对于您来说应该已经足够了,因为您是VB.NET开发人员并且该解决方案与语言无关:
public interface IMyControl
{
void Do();
}
public class SpecializedTextBox : TextBox, IMyControl
{
private readonly MyControlExtension _extension = new MyControlExtension(this);
public MyControlExtension Extension
{
get { return _extension; }
}
public void Do()
{
Extension.Do();
}
}
public class MyControlExtension
{
public MyControlExtension(Control wrappedControl)
{
_wrappedControl = wrappedControl;
}
private readonly Control _wrappedControl;
public Control WrappedControl { get { return _wrapedControl; } }
public void Do()
{
// Do some stuff with the WrappedControl property contained control
}
}
现在SpecializedTextBox
控件同时包含IMyControl
和TextBox
成员。
据我所知,这足以模拟多继承,因为类可以实现一个或多个接口。
答案 1 :(得分:1)