Cómo: Obtener y establecer propiedades en el ámbito de aplicación

En este ejemplo se muestra cómo obtener y establecer propiedades del ámbito de aplicación mediante Properties.

Ejemplo

Application expone un almacén de datos para las propiedades que se pueden compartir en un AppDomain: Properties.

El almacén de datos de propiedad es un diccionario de pares de clave/valor que se pueden utilizar así:

      ' 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"];

Debe tener en cuenta dos aspectos al utilizar Properties. En primer lugar, la clave de diccionario es un objeto, por lo que es preciso utilizar exactamente la misma instancia del objeto al establecer y obtener un valor de propiedad (tenga en cuenta que la clave distingue entre mayúsculas y minúsculas cuando se utiliza una clave de cadena). En segundo lugar, el valor del diccionario es un objeto, por lo que deberá convertir el valor al tipo que desee cuando obtenga un valor de propiedad.

Dado que el valor de diccionario es un objeto, resulta igual de fácil utilizar tipos personalizados o tipos simples, así:

      ' 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"];

Vea también

Referencia

IDictionary