假设我的应用程序有大约300种形式的标准控件。总有一天,它将是最好的给予所有的控制额外的成员。
必须做些什么?我的想法是:
从这样的基类派生出每种类型的Control:
public partial class MyButton : Button, MyInterface
{
...
}
public partial class MyTextBox : TextBox, MyInterface
{
...
}
public interface MyInterface
{
// Additional members
...
}这意味着触摸每一个Control以将其更改为
private System.Windows.Forms.Button myButton;
private System.Windows.Forms.TextBox myTextBox;至
private MyButton myButton;
private MyTextBox myTextBox;和来自
this.myButton = new System.Windows.Forms.Button();
this.myTextBox = new System.Windows.Forms.TextBox();至
this.myButton = new MyButton();
this.myTextBox = new MyTextBox();我的问题是:有更简单的方法吗?也许,如果可能的话,将Control类替换为另外从MyInterface派生的类?(Control.Tag属性不可选)
发布于 2017-02-06 22:57:19
创建扩展程序提供程序似乎是一个很好的选择。ToolTip是一个示例;当您向窗体添加一个ToolTip时,它会向所有控件添加一个ToolTip on ToolTip1字符串属性。
扩展程序提供程序向其他组件提供属性。您可以设计扩展程序组件,以便将不同(简单或复杂)类型的属性添加到不同的控件类型中。扩展程序提供程序提供的属性实际上驻留在扩展程序提供程序对象本身中,因此不是它修改的组件的真正属性。在设计时,属性出现在“属性”窗口中。在运行时,可以调用扩展程序组件上的getter和setter方法。
资源
示例
下面是一个非常简单的示例组件,它将字符串SomeProperty属性添加到TextBox和Button中。该属性是一个简单的属性,没有实际使用,但它是您的起点:
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
[ProvideProperty("SomeProperty", typeof(Control))]
public class ControlExtender : Component, IExtenderProvider
{
private Hashtable somePropertyValues = new Hashtable();
public bool CanExtend(object extendee)
{
return (extendee is TextBox ||
extendee is Button);
}
public string GetSomeProperty(Control control)
{
if (somePropertyValues.ContainsKey(control))
return (string)somePropertyValues[control];
return null;
}
public void SetSomeProperty(Control control, string value)
{
if (string.IsNullOrEmpty(value))
somePropertyValues.Remove(control);
else
somePropertyValues[control] = value;
}
}发布于 2017-02-06 16:33:44
我不会这么做的。控件的正常工作不改变,只想存储一些额外的信息?我将使用全局字典,其中MyExtension类包含所有成员将添加到您的MyInterface中。
发布于 2017-02-06 16:35:11
如果只想添加方法,可以简单地使用扩展方法。
否则,我建议您创建接口来定义通用/特定行为,为这些接口的一般实现定义抽象类(继承经典控件),并最终使您的类从这些抽象类继承。但正如你提到的那样,你将不得不重新命名它的所有。(您可以想象使用名称空间来避免更改名称或将成员动态添加到类中的技巧,但我不建议这样做)。
https://stackoverflow.com/questions/42072389
复制相似问题