【发布时间】:2016-02-28 06:35:48
【问题描述】:
我继承了一些System.Windows.Forms-Control(大约10个)。
他们每个人都有一些自定义扩展,但大多数扩展对于每个控件都是相同的。
实际上,我必须为它们中的每一个单独编写相同的功能。 这需要大量的复制和粘贴,并且难以维护。
class MyButton : Button
{
//this is only in MyButton
public int ButtonProperty { get; set; }
public object Property1 { get; set; }
public object Property2 { get; set; }
public void MakeInvisible()
{
this.Visible = false;
}
}
class MyLabel : Label
{
//this is only in MyLabel
public bool LabelProperty { get; set; }
//same propertys and methods as in MyButton
public object Property1 { get; set; }//copy+paste
public object Property2 { get; set; }//copy+paste
public void MakeInvisible()//copy+paste
{
this.Visible = false;
}
}
我正在寻找的是一种扩展所有派生类的方法,就像您可以使用 interface 或扩展方法一样。 但我也想拥有属性并访问基类 (Control)
这就是我的梦想:
class MyButton : Button, MyExtension
{
//this is only in MyButton
public int ButtonProperty { get; set; }
}
class MyLabel : Label, MyExtension
{
//this is only in MyLabel
public bool LabelProperty { get; set; }
}
//Extension for all classes inherited from Control
class MyExtension : Control
{
public object Property1 { get; set; }
public object Property2 { get; set; }
public void MakeInvisible()
{
this.Visible = false;
}
}
【问题讨论】:
-
我认为您应该对控件使用组合而不是继承,然后它是一个简单的基类和子类设置。
-
你的意思是这样的?
class MyButton : Button { public MyExtension = new MyExtension();} -
不,请参阅我的回答以了解我所说的示例。
标签: c# .net class controls extension-methods