Share via


HOW TO:取得和設定應用程式範圍的屬性

本範例顯示如何使用 Properties,取得和設定應用程式範圍的屬性。

範例

Application 會公開 (Expose) 可共用於 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 時,需要進行兩項考量。 首先,字典 key 是個物件,所以在設定和取得屬性值時,您必須使用完全相同的物件執行個體 (請注意,使用字串索引鍵時索引鍵必須區分大小寫)。 第二,字典 value 是個物件,所以在取得屬性值時,您必須將此值轉換為所需的型別。

因為字典值為物件,所以您可如同使用簡單型別一樣輕易地使用自訂型別,如下所示:

      ' 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