繁体   English   中英

C#-从派生的方法中隐藏UserControl类的所有方法

[英]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中隐藏。 但是这些方法仍然存在,并且仍然可以调用。 通常,无法禁止客户端在类的实例上调用继承的方法。

您有一些选择:

  1. 使用EditorBrowsableAttribute将隐藏智能感知的属性
  2. 使用BrowsableAttribute将隐藏属性网格中的属性
  3. 使用“ private new”隐藏属性本身会将其隐藏

注意事项:

  1. 使用属性将隐藏属性,具体取决于“消费者”的实现,但是在语言级别,您没有隐藏任何内容。 例如,您可以实现一个属性网格,该网格在显示属性之前会检查EditorBrowsableAttribute。 [我不确定Microsoft的Windows窗体实现]
  2. 使用“ private new”也将阻止您访问属性,尽管在控件内部您仍可以调用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM