次の方法で共有


コンテナーとコンポーネントの間のやり取り

コンテナーは、それに含まれるコンポーネントとクライアント アプリケーションとの間のやり取りを媒介するものです。 アプリケーションは、コンポーネントの実際の名前や ID を知らなくても、コンテナー内でコンポーネントへの参照を取得できます。 コンポーネントは、コンテナーを通じてさまざまな方法でクライアント アプリケーションとやり取りできます。

コンテナー オブジェクトは、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 Method を呼び出してコンテナーからサービスを取得することもできます。 このメソッドは、次に示すように、指定された型のオブジェクトを返します。

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 メソッドをオーバーライドして、実装されたサービス オブジェクトを提供するようにコーディングします。

参照

処理手順

方法 : コンポーネント コンテナーを作成する

方法 : コンポーネント コンテナーを拡張する

概念

コンテナー、Site、およびコンポーネント