1

我有一个自定义用户控件。通常它继承UserControl类。但是通过这种方式,它继承了所有的公共方法和属性UserControl。但我想隐藏所有这些并实现我自己的一些方法和属性。

假设我有一个名为CustomControl.

public class CustomControl : UserControl

当我创建一个实例时CustomControl

CustomControl cControl = new CustomControl();

当我键入时,cControl.intellisense 为我提供了从UserControl. 但我只想列出我在CustomControl课堂上实现的。

4

7 回答 7

6

你可以创建一个接口,然后只暴露接口的方法和属性。

public interface ICustomControl {
     string MyProperty { get; set;}
}

public class CustomControl : UserControl, ICustomControl {
     public string MyProperty { get; set; }
}

...

ICustomControl cControl = new CustomControl();

然后智能感知只显示 MyProperty 和 Object 的成员(以及扩展方法,如果有的话)。

编辑:

protected ICustomControl CustomControl { get; set; }
    public Form1()
    {
        InitializeComponent();
        CustomControl = this.customControl1;
        CustomControl.MyProperty = "Hello World!"; // Access everything through here.
    }

然后,您可以根据需要将 CustomControl 的范围设置为内部或受保护的内部。

于 2009-11-19T00:04:10.987 回答
4

这不是继承的工作方式。通过创建子类,您明确表示您希望所有基类的方法和属性都可以访问。

于 2009-11-19T00:01:53.230 回答
1

你有一些选择:

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

需要考虑的事项:

  1. 使用属性将根据“消费者”的实现隐藏属性,但在语言级别上,您并没有隐藏任何东西。例如,您可以实现一个属性网格,在显示属性之前检查 EditorBrowsableAttribute。[我不确定微软的 Windows Forms 实现]
  2. 使用“private new”也将阻止您访问属性,但是,在您的控件内部,您仍然可以调用base.PropertyName以访问原始属性。

我明白你的意图。通常会限制继承控件的行为,即使它“破坏”了继承概念。

于 2009-11-19T00:06:38.750 回答
1

为什么不使用组合并使 UserControl 成为自定义控件的成员,而不是从它继承?

于 2009-11-18T23:59:43.437 回答
1

new您可以通过在您的类中隐藏它们(使用关键字重新声明每个继承的方法)并将它们应用于它们,从而从 IntelliSense 中隐藏EditorBrowsableAttribute它们。但是这些方法仍然存在,并且仍然是可调用的。一般来说,没有办法禁止客户端在您的类的实例上调用继承的方法。

于 2009-11-19T00:01:39.180 回答
0

不要继承UserControlControl而是继承。

于 2009-11-18T23:59:59.660 回答
0

你可以通过聚合来做到这一点,例如

public CustomControl
{
    private Control control_;
    public property control {get{ return _control;}}
    .
    .
    .
    public void FunctionIWantExposed() {}
}

但这并不是特别有用。您将无法将其添加到任何控件集合中。您可以在自定义类控件中使用该属性并将其添加到控件集合中,但是您尝试隐藏的所有这些方法都会再次暴露。

于 2009-11-19T00:04:36.047 回答