ConfigurationPropertyAttribute Clase

Definición

De forma declarativa, indica a .NET que cree una instancia de una propiedad de configuración. Esta clase no puede heredarse.

public ref class ConfigurationPropertyAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Property)]
public sealed class ConfigurationPropertyAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Property)>]
type ConfigurationPropertyAttribute = class
    inherit Attribute
Public NotInheritable Class ConfigurationPropertyAttribute
Inherits Attribute
Herencia
ConfigurationPropertyAttribute
Atributos

Ejemplos

En el ejemplo siguiente se muestra cómo definir las propiedades de un objeto personalizado ConfigurationSection mediante el ConfigurationPropertyAttribute atributo .

El ejemplo contiene dos clases. La UrlsSection clase personalizada usa ConfigurationPropertyAttribute para definir sus propias propiedades. La UsingConfigurationPropertyAttribute clase usa UrlsSection para leer y escribir la sección personalizada en el archivo de configuración de la aplicación.

using System;
using System.Configuration;

// Define a custom section.
// This class shows how to use the ConfigurationPropertyAttribute.
public class UrlsSection : ConfigurationSection
{
    [ConfigurationProperty("name", DefaultValue = "Contoso",
        IsRequired = true, IsKey = true)]
    public string Name
    {
        get
        {
            return (string)this["name"];
        }
        set
        {
            this["name"] = value;
        }
    }

    [ConfigurationProperty("url", DefaultValue = "http://www.contoso.com",
        IsRequired = true)]
    [RegexStringValidator(@"\w+:\/\/[\w.]+\S*")]
    public string Url
    {
        get
        {
            return (string)this["url"];
        }
        set
        {
            this["url"] = value;
        }
    }

    [ConfigurationProperty("port", DefaultValue = (int)0, IsRequired = false)]
    [IntegerValidator(MinValue = 0, MaxValue = 8080, ExcludeRange = false)]
    public int Port
    {
        get
        {
            return (int)this["port"];
        }
        set
        {
            this["port"] = value;
        }
    }
}
Imports System.Configuration


' Define a custom section.
' This class shows how to use the ConfigurationPropertyAttribute.
Public Class UrlsSection
    Inherits ConfigurationSection
    <ConfigurationProperty("name", DefaultValue:="Contoso", IsRequired:=True, IsKey:=True)>
    Public Property Name() As String
        Get
            Return CStr(Me("name"))
        End Get
        Set(ByVal value As String)
            Me("name") = value
        End Set
    End Property

    <ConfigurationProperty("url", DefaultValue:="http://www.contoso.com", IsRequired:=True), RegexStringValidator("\w+:\/\/[\w.]+\S*")>
    Public Property Url() As String
        Get
            Return CStr(Me("url"))
        End Get
        Set(ByVal value As String)
            Me("url") = value
        End Set
    End Property

    <ConfigurationProperty("port", DefaultValue:=0, IsRequired:=False), IntegerValidator(MinValue:=0, MaxValue:=8080, ExcludeRange:=False)>
    Public Property Port() As Integer
        Get
            Return CInt(Fix(Me("port")))
        End Get
        Set(ByVal value As Integer)
            Me("port") = value
        End Set
    End Property
End Class
using System;
using System.Configuration;

public class UsingConfigurationPropertyAttribute
{

    // Create a custom section and save it in the 
    // application configuration file.
    static void CreateCustomSection()
    {
        try
        {

            // Create a custom configuration section.
            UrlsSection customSection = new UrlsSection();

            // Get the current configuration file.
            System.Configuration.Configuration config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None);

            // Add the custom section to the application
            // configuration file.
            if (config.Sections["CustomSection"] == null)
            {
                config.Sections.Add("CustomSection", customSection);
            }

            // Save the application configuration file.
            customSection.SectionInformation.ForceSave = true;
            config.Save(ConfigurationSaveMode.Modified);

            Console.WriteLine("Created custom section in the application configuration file: {0}",
                config.FilePath);
            Console.WriteLine();
        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("CreateCustomSection: {0}", err.ToString());
        }
    }

    static void ReadCustomSection()
    {
        try
        {
            // Get the application configuration file.
            System.Configuration.Configuration config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None) as Configuration;

            // Read and display the custom section.
            UrlsSection customSection =
                config.GetSection("CustomSection") as UrlsSection;
            Console.WriteLine("Reading custom section from the configuration file.");
            Console.WriteLine("Section name: {0}", customSection.Name);
            Console.WriteLine("Url: {0}", customSection.Url);
            Console.WriteLine("Port: {0}", customSection.Port);
            Console.WriteLine();
        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("ReadCustomSection(string): {0}", err.ToString());
        }
    }
    
    static void Main(string[] args)
    {
       
        // Get the name of the application.
        string appName =
            Environment.GetCommandLineArgs()[0];

        // Create a custom section and save it in the 
        // application configuration file.
        CreateCustomSection();

        // Read the custom section saved in the
        // application configuration file.
        ReadCustomSection();

        Console.WriteLine("Press enter to exit.");

        Console.ReadLine();
    }
}
Imports System.Configuration

Public Class UsingConfigurationPropertyAttribute

    ' Create a custom section and save it in the 
    ' application configuration file.
    Private Shared Sub CreateCustomSection()
        Try

            ' Create a custom configuration section.
            Dim customSection As New UrlsSection()

            ' Get the current configuration file.
            Dim config As System.Configuration.Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)

            ' Add the custom section to the application
            ' configuration file.
            If config.Sections("CustomSection") Is Nothing Then
                config.Sections.Add("CustomSection", customSection)
            End If


            ' Save the application configuration file.
            customSection.SectionInformation.ForceSave = True
            config.Save(ConfigurationSaveMode.Modified)

            Console.WriteLine("Created custom section in the application configuration file: {0}", config.FilePath)
            Console.WriteLine()

        Catch err As ConfigurationErrorsException
            Console.WriteLine("CreateCustomSection: {0}", err.ToString())
        End Try

    End Sub

    Private Shared Sub ReadCustomSection()
        Try
            ' Get the application configuration file.
            Dim config As System.Configuration.Configuration = TryCast(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None), Configuration)

            ' Read and display the custom section.
            Dim customSection As UrlsSection = TryCast(config.GetSection("CustomSection"), UrlsSection)
            Console.WriteLine("Reading custom section from the configuration file.")
            Console.WriteLine("Section name: {0}", customSection.Name)
            Console.WriteLine("Url: {0}", customSection.Url)
            Console.WriteLine("Port: {0}", customSection.Port)
            Console.WriteLine()
        Catch err As ConfigurationErrorsException
            Console.WriteLine("ReadCustomSection(string): {0}", err.ToString())
        End Try

    End Sub

    Shared Sub Main(ByVal args() As String)

        ' Get the name of the application.
        Dim appName As String = Environment.GetCommandLineArgs()(0)

        ' Create a custom section and save it in the 
        ' application configuration file.
        CreateCustomSection()

        ' Read the custom section saved in the
        ' application configuration file.
        ReadCustomSection()

        Console.WriteLine("Press enter to exit.")

        Console.ReadLine()
    End Sub
End Class

A continuación se muestra un extracto del archivo de configuración que contiene la sección personalizada tal como se define en el ejemplo anterior.

<?xml version="1.0" encoding="utf-8"?>  
<configuration>  
    <configSections>  
        <section name="CustomSection" type="UrlsSection, UsingConfigurationPropertyAttribute, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />  
    </configSections>  
    <CustomSection name="Contoso" url="http://www.contoso.com" />  
</configuration>  

Comentarios

Se usa ConfigurationPropertyAttribute para decorar una propiedad de configuración, que indicará a .NET que cree una instancia y que inicialice la propiedad con el valor del parámetro de decoración.

Nota

La manera más sencilla de crear un elemento de configuración personalizado es usar el modelo con atributos (declarativos). Las propiedades públicas personalizadas se declaran y se decoran con el ConfigurationPropertyAttribute atributo . Para cada propiedad marcada con este atributo, .NET usa la reflexión para leer los parámetros de decoración y crear una instancia relacionada ConfigurationProperty . También puede usar el modelo de programación, en cuyo caso es su responsabilidad declarar las propiedades públicas personalizadas y devolver su colección.

El sistema de configuración de .NET proporciona tipos de atributo que puede usar durante la creación de elementos de configuración personalizados. Hay dos tipos de tipos de atributo:

  1. Los tipos que indican a .NET cómo crear instancias de las propiedades personalizadas del elemento de configuración. Estos tipos incluyen:

  2. Los tipos que indican a .NET cómo validar las propiedades personalizadas del elemento de configuración. Estos tipos incluyen:

Constructores

ConfigurationPropertyAttribute(String)

Inicializa una nueva instancia de la clase ConfigurationPropertyAttribute.

Propiedades

DefaultValue

Obtiene o establece el valor predeterminado de la propiedad representativa.

IsDefaultCollection

Obtiene o establece un valor que indica si ésta es la colección de propiedades predeterminada para la propiedad de configuración representativa.

IsKey

Obtiene o establece un valor que indica si ésta es una propiedad clave para la propiedad representativa de elemento.

IsRequired

Obtiene o establece un valor que indica si se requiere la propiedad representativa de elemento.

Name

Obtiene el nombre de la propiedad representativa de elemento de configuración.

Options

Obtiene o establece la enumeración ConfigurationPropertyOptions para la propiedad representativa de elemento de configuración.

TypeId

Cuando se implementa en una clase derivada, obtiene un identificador único para este Attribute.

(Heredado de Attribute)

Métodos

Equals(Object)

Devuelve un valor que indica si esta instancia es igual que un objeto especificado.

(Heredado de Attribute)
GetHashCode()

Devuelve el código hash de esta instancia.

(Heredado de Attribute)
GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
IsDefaultAttribute()

Si se reemplaza en una clase derivada, indica si el valor de esta instancia es el valor predeterminado de la clase derivada.

(Heredado de Attribute)
Match(Object)

Cuando se invalida en una clase derivada, devuelve un valor que indica si esta instancia es igual a un objeto especificado.

(Heredado de Attribute)
MemberwiseClone()

Crea una copia superficial del Object actual.

(Heredado de Object)
ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)

Implementaciones de interfaz explícitas

_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Asigna un conjunto de nombres a un conjunto correspondiente de identificadores de envío.

(Heredado de Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Obtiene la información de tipos de un objeto, que puede utilizarse para obtener la información de tipos de una interfaz.

(Heredado de Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Recupera el número de interfaces de información de tipo que proporciona un objeto (0 ó 1).

(Heredado de Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Proporciona acceso a las propiedades y los métodos expuestos por un objeto.

(Heredado de Attribute)

Se aplica a

Consulte también