容器與元件之間的通訊

更新:2007 年 11 月

容器是用戶端應用程式與其所包含元件之間的通訊管道。應用程式可在容器內取得元件的參考,而不需要知道元件的確實的名稱或是識別。元件也能透過容器,以各種不同的方式與用戶端應用程式互動。

容器物件透過其 Components 屬性來公開它所包含的元件。這個屬性是傳回 IComponent 參考物件的索引屬性。元件則是以先進先出的方式來追蹤,且可透過索引存取,使用的語法如下:

Imports System.ComponentModel
Dim MyContainer As Container
Dim xComponent as IComponent
xComponent = MyContainer.Components(0)
using System.ComponentModel;
Container MyContainer = new Container();
IComponent xComponent;
xComponent = MyContainer.Components[0];

無論是否具有名稱,元件都可加入容器當中。如果您知道所參考元件的名稱,您也可以使用這個名稱來透過容器取得參考,如以下範例所示:

xComponent = MyContainer.Components("myComponent")
xComponent = MyContainer.Components["myComponent"];

請注意,Components 屬性會傳回 IComponent 參考,而且不允許您存取不是由這個介面所實作的元件方法和屬性。

元件主要是透過其 Site 屬性來與容器通訊。透過 Site,元件能夠取得 IContainer 介面 (由容器實作) 的參考,如以下所示:

Dim myComponent As New Component()
Dim myIContainer as IContainer
myIContainer = myComponent.Site.Container
Component myComponent = new Component();
IContainer myIContainer;
myIContainer = myComponent.Site.Container;

Container 屬性也會傳回相同的參考。這可視為一種捷徑:參考仍然是透過 ISite 物件來提供,但不是利用明確的方式。

元件也可以藉由呼叫 IServiceProvider.GetService 方法來從容器取得服務 (如果有提供的話)。這個方法會傳回指定型別的物件,如以下所示:

Dim myComponent As Component
Dim myWidget As Widget
Dim serviceObject As Object
' This returns an object of type Widget that is supplied by the container.
serviceObject = myComponent.Site.GetService(GetType(Widget))
myWidget = CType(serviceObject, Widget)
Component myComponent = new Component();
Widget myWidget;
object serviceObject;
// This returns an object of type Widget that is supplied by the container.
serviceObject = myComponent.Site.GetService(System.Type.GetType("CommunicateCS.Widget"));
myWidget = (Widget)serviceObject;

若要透過 GetService 接收物件,它必須先在繼承容器類別中進行實作。若要提供實作的服務物件,應將 Container 類別的 GetService 方法加以覆寫及編碼。

請參閱

工作

HOW TO:建立元件容器

HOW TO:擴充元件容器

概念

容器、站台和元件