[英]C# - Hiding all methods of the UserControl class from a derived one
我有一个自定义的用户控件。 通常,它继承UserControl
类。 但是通过这种方式,它继承了UserControl
所有公共方法和属性。 但是我想隐藏所有这些并实现我自己的一些方法和属性。
假设我有一个名为CustomControl
的自定义控件。
public class CustomControl : UserControl
当我创建CustomControl
的实例时:
CustomControl cControl = new CustomControl();
当我键入cControl.
intellisense为我提供了从UserControl
派生的所有方法和属性。 但是我只想列出在CustomControl
类中实现的我的。
您可以创建一个接口,然后仅公开该接口的方法和属性。
public interface ICustomControl {
string MyProperty { get; set;}
}
public class CustomControl : UserControl, ICustomControl {
public string MyProperty { get; set; }
}
...
ICustomControl cControl = new CustomControl();
然后,Intellisense仅显示MyProperty和Object的成员(以及扩展方法,如果有的话)。
编辑:
protected ICustomControl CustomControl { get; set; }
public Form1()
{
InitializeComponent();
CustomControl = this.customControl1;
CustomControl.MyProperty = "Hello World!"; // Access everything through here.
}
然后,您可以根据需要将CustomControl的范围设置为内部或受保护的内部。
继承不是这样工作的。 通过创建子类,您明确表示您希望访问所有基类的方法和属性。
为什么不使用组合并使UserControl成为自定义控件的成员,而不是从其继承?
您可以通过在类中对其进行阴影处理(用关键字new
声明每个继承的方法),然后将EditorBrowsableAttribute
应用于它们,从而将它们从IntelliSense中隐藏。 但是这些方法仍然存在,并且仍然可以调用。 通常,无法禁止客户端在类的实例上调用继承的方法。
您有一些选择:
EditorBrowsableAttribute
将隐藏智能感知的属性 BrowsableAttribute
将隐藏属性网格中的属性 注意事项:
base.PropertyName
来访问原始属性。 我明白你的意图。 即使“继承”继承概念,通常也会限制继承控件的行为。
不要继承UserControl
,而是继承Control
。
您可以通过聚合来做到这一点,例如
public CustomControl
{
private Control control_;
public property control {get{ return _control;}}
.
.
.
public void FunctionIWantExposed() {}
}
但这并不是特别有用。 您将无法将其添加到任何控件集合中。 您可以在自定义类控件中使用该属性,并将其添加到ControlsCollection中,但是随后您尝试隐藏的所有这些方法将再次公开。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.