次の方法で共有


方法 : アプリケーション スコープのプロパティを取得および設定する

この例では、Properties を使用してアプリケーション スコープのプロパティを取得および設定する方法について説明します。

使用例

Application は、AppDomain 全体で共有できるプロパティ用のデータ ストアである Properties を公開します。

プロパティ データ ストアはキーと値のペアから成るディクショナリで、次のように使用できます。

      ' Set an application-scope property
      Application.Current.Properties("MyApplicationScopeProperty") = "myApplicationScopePropertyValue"
// Set an application-scope property
Application.Current.Properties["MyApplicationScopeProperty"] = "myApplicationScopePropertyValue";
      ' Get an application-scope property
      ' NOTE: Need to convert since Application.Properties is a dictionary of System.Object
      Dim myApplicationScopeProperty As String = CStr(Application.Current.Properties("MyApplicationScopeProperty"))
// Get an application-scope property
// NOTE: Need to convert since Application.Properties is a dictionary of System.Object
string myApplicationScopeProperty = (string)Application.Current.Properties["MyApplicationScopeProperty"];

Properties を使用するときに注意すべき点が 2 つあります。 まず、ディクショナリのキーがオブジェクトであるため、プロパティ値を設定したり取得したりするときには、まったく同じオブジェクト インスタンスを使用する必要があります (文字列キーを使用する場合、キーは大文字と小文字を区別します)。 2 つ目に、ディクショナリの値がオブジェクトであるため、プロパティ値を取得するときにその値を目的の型に変換する必要があります。

ディクショナリの値はオブジェクトなので、次のように、単純型と同じように簡単にカスタム型を使用できます。

      ' Set an application-scope property with a custom type
      Dim customType As New CustomType()
      Application.Current.Properties("CustomType") = customType
// Set an application-scope property with a custom type
CustomType customType = new CustomType();
Application.Current.Properties["CustomType"] = customType;
      ' Get an application-scope property
      ' NOTE: Need to convert since Application.Properties is a dictionary of System.Object
      Dim customType As CustomType = CType(Application.Current.Properties("CustomType"), CustomType)
// Get an application-scope property
// NOTE: Need to convert since Application.Properties is a dictionary of System.Object
CustomType customType = (CustomType)Application.Current.Properties["CustomType"];

参照

参照

IDictionary