ConfigurationPropertyAttribute ConfigurationPropertyAttribute ConfigurationPropertyAttribute ConfigurationPropertyAttribute Class

Definición

Mediante declaración, le indica a .NET Framework que cree instancias de una propiedad de configuración.Declaratively instructs the .NET Framework to instantiate a configuration property. Esta clase no puede heredarse.This class cannot be inherited.

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

Ejemplos

En el ejemplo siguiente se muestra cómo definir las propiedades de un ConfigurationSection objeto personalizado mediante ConfigurationPropertyAttribute el atributo.The following example shows how to define the properties of a custom ConfigurationSection object using the ConfigurationPropertyAttribute attribute.

El ejemplo contiene dos clases.The example contains two classes. La UrlsSection clase personalizada ConfigurationPropertyAttribute utiliza para definir sus propias propiedades.The UrlsSection custom class uses the ConfigurationPropertyAttribute to define its own properties. La UsingConfigurationPropertyAttribute claseUrlsSection utiliza para leer y escribir la sección personalizada en el archivo de configuración de la aplicación.The UsingConfigurationPropertyAttribute class uses the UrlsSection to read and write the custom section in the application configuration file.

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 Microsoft.VisualBasic
Imports System
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
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 y como se define en el ejemplo anterior.The following is an excerpt of the configuration file containing the custom section as defined in the previous sample.

<?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

Utilice ConfigurationPropertyAttribute para decorar una propiedad de configuración, que indicará a la .NET Framework que cree una instancia e inicialice la propiedad mediante el valor del parámetro de decoración.You use the ConfigurationPropertyAttribute to decorate a configuration property, which will instruct the .NET Framework to instantiate and to initialize the property using the value of the decorating parameter.

Nota

La manera más sencilla de crear un elemento de configuración personalizado es usar el modelo con atributos (declarativo).The simplest way to create a custom configuration element is to use the attributed (declarative) model. Puede declarar las propiedades públicas personalizadas y decorarlas con el ConfigurationPropertyAttribute atributo.You declare the custom public properties and decorate them with the ConfigurationPropertyAttribute attribute. Para cada propiedad marcada con este atributo, el .NET Framework utiliza la reflexión para leer los parámetros de decoración y crear ConfigurationProperty una instancia relacionada.For each property marked with this attribute, the .NET Framework uses reflection to read the decorating parameters and create a related ConfigurationProperty instance. 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.You can also use the programmatic model, in which case it is your responsibility to declare the custom public properties and return their collection.

El sistema de configuración de .NET Framework proporciona tipos de atributos que se pueden usar durante la creación de elementos de configuración personalizados.The .NET Framework configuration system provides attribute types that you can use during the creation of custom configuration elements. Hay dos tipos de atributos:There are two kinds of attribute types:

  1. Los tipos que indican a la .NET Framework cómo crear una instancia de las propiedades de elemento de configuración personalizadas.The types instructing the .NET Framework how to instantiate the custom configuration-element properties. Estos tipos incluyen:These types include:

  2. Los tipos que indican a la .NET Framework cómo validar las propiedades personalizadas del elemento de configuración.The types instructing the .NET Framework how to validate the custom configuration-element properties. Estos tipos incluyen:These types include:

Constructores

ConfigurationPropertyAttribute(String) ConfigurationPropertyAttribute(String) ConfigurationPropertyAttribute(String) ConfigurationPropertyAttribute(String)

Inicializa una nueva instancia de la clase ConfigurationPropertyAttribute.Initializes a new instance of ConfigurationPropertyAttribute class.

Propiedades

DefaultValue DefaultValue DefaultValue DefaultValue

Obtiene o establece el valor predeterminado de la propiedad representativa.Gets or sets the default value for the decorated property.

IsDefaultCollection IsDefaultCollection IsDefaultCollection IsDefaultCollection

Obtiene o establece un valor que indica si ésta es la colección de propiedades predeterminada para la propiedad de configuración representativa.Gets or sets a value indicating whether this is the default property collection for the decorated configuration property.

IsKey IsKey IsKey IsKey

Obtiene o establece un valor que indica si ésta es una propiedad clave para la propiedad representativa de elemento.Gets or sets a value indicating whether this is a key property for the decorated element property.

IsRequired IsRequired IsRequired IsRequired

Obtiene o establece un valor que indica si se requiere la propiedad representativa de elemento.Gets or sets a value indicating whether the decorated element property is required.

Name Name Name Name

Obtiene el nombre de la propiedad representativa de elemento de configuración.Gets the name of the decorated configuration-element property.

Options Options Options Options

Obtiene o establece la enumeración ConfigurationPropertyOptions para la propiedad representativa de elemento de configuración.Gets or sets the ConfigurationPropertyOptions for the decorated configuration-element property.

TypeId TypeId TypeId TypeId

Cuando se implementa en una clase derivada, obtiene un identificador único para este Attribute.When implemented in a derived class, gets a unique identifier for this Attribute.

(Inherited from Attribute)

Métodos

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Devuelve un valor que indica si esta instancia es igual que un objeto especificado.Returns a value that indicates whether this instance is equal to a specified object.

(Inherited from Attribute)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Devuelve el código hash de esta instancia.Returns the hash code for this instance.

(Inherited from Attribute)
GetType() GetType() GetType() GetType()

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

(Inherited from Object)
IsDefaultAttribute() IsDefaultAttribute() IsDefaultAttribute() IsDefaultAttribute()

Si se reemplaza en una clase derivada, indica si el valor de esta instancia es el valor predeterminado de la clase derivada.When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class.

(Inherited from Attribute)
Match(Object) Match(Object) Match(Object) Match(Object)

Cuando se invalida en una clase derivada, devuelve un valor que indica si esta instancia es igual a un objeto especificado.When overridden in a derived class, returns a value that indicates whether this instance equals a specified object.

(Inherited from Attribute)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Crea una copia superficial del objeto Object actual.Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

Devuelve una cadena que representa el objeto actual.Returns a string that represents the current object.

(Inherited from Object)

Implementaciones de interfaz explícitas

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

Asigna un conjunto de nombres a un conjunto correspondiente de identificadores de envío.Maps a set of names to a corresponding set of dispatch identifiers.

(Inherited from Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _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.Retrieves the type information for an object, which can be used to get the type information for an interface.

(Inherited from Attribute)
_Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32)

Recupera el número de interfaces de información de tipo que proporciona un objeto (0 ó 1).Retrieves the number of type information interfaces that an object provides (either 0 or 1).

(Inherited from Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Proporciona acceso a las propiedades y los métodos expuestos por un objeto.Provides access to properties and methods exposed by an object.

(Inherited from Attribute)

Se aplica a

Consulte también: