如何:扩展组件容器

组件容器是完全可扩展的。 可以从 Container 类继承和添加属性或方法,添加强制规则的自定义功能,重写基方法或希望容器合并的任何其他自定义功能。 有关容器和扩展容器的详细信息,请参见容器、站点和组件

像扩展任何基类那样扩展 Container。 创建继承基类属性的类,重写任何要扩展的基方法,并添加任何所需的附加属性或方法。 然后可以像对待标准 Container 那样使用新类,并使用任何已编码的新功能。

扩展 Container 基类

  1. 声明从 Container 类集成的新类。

    Public Class myContainer
       Inherits System.ComponentModel.Container
    End Class
    
    class myContainer: System.ComponentModel.Container
    {
    }
    
    class myContainer
       extends System.ComponentModel.Container
    {
    }
    
  2. 重写任何基类方法以添加附加功能。 下面的示例显示如何重写 Add 方法。

    提示

    Container 实际上有两个 Add 重载,在本例中需要提供每个重载的重写。

    ' Because Add is overloaded, this line includes the Overloads keyword.
    Public Overloads Overrides Sub Add(ByVal component As _
       System.ComponentModel.IComponent)
       ' Determines if the component can be added to the container.
       If TypeOf component Is Widget Then
          ' Calls the base Add function to add the component.
          MyBase.Add(component)
       Else
          ' Throws an exception.
          Throw New NonWidgetException()
       End If
    End Sub
    
    public override void Add(System.ComponentModel.IComponent component)
    {
       if (component is Widget)
          base.Add(component);
       else 
       {
          throw(new NonWidgetException());
       }
    }
    
    public void Add(System.ComponentModel.IComponent component)
       throws NonWidgetException
    {
       if ( component instanceof Widget  ) {
          super.Add(component);
       }
       else
       {
          throw new NonWidgetException() ;
       }
    }
    
  3. 添加希望新容器合并的任何新属性或方法。

请参见

任务

如何:创建组件容器

参考

Container

概念

容器、站点和组件

容器和组件之间的通信