Este artigo foi traduzido por máquina. Coloque o ponteiro do mouse sobre as frases do artigo para ver o texto original. Mais informações.
Tradução
Original
Este tópico ainda não foi avaliado como - Avalie este tópico

ConfigurationProperty Classe

Esta API não oferece suporte a infra-estrutura do .NET Framework e a ser usado diretamente a partir de seu código.

Representa um atributo ou um elemento de configuração filho. Esta classe não pode ser herdada.

Namespace:  System.Configuration
Assembly:  System.Configuration (em System.Configuration. dll)
public sealed class ConfigurationProperty

In the case of a simple ConfigurationElement, such as the CustomSection shown in the next example, the ConfigurationProperty objects represent attributes such as fileName.

In the case of more complex configuration elements such as a section containing subsections, for instance authentication, the ConfigurationProperty objects can represent ConfigurationElement objects as well as attributes.

The ConfigurationPropertyCollection class represents the collection of the ConfigurationProperty objects that can be either attributes or ConfigurationElement objects of a configuration element.

The ConfigurationProperty class represents an individual configuration setting.Esta classe permite obter ou definir o nome, tipo e valor padrão para uma entidade de configuração específica (atributo ou elemento) e especifique se o atributo é necessário, é uma chave elemento ou, representa uma coleção elemento padrão.

OBSERVAÇÕES PARA Implementers:

Every ConfigurationElement object creates an internal ConfigurationPropertyCollection collection of ConfigurationProperty objects that represents either the element attributes or a collection of child elements.

Non-customizable information and functionality is contained by an ElementInformation object provided by the ElementInformation property.

You can use a or a () Coding to Criar a .

  • Modelo através de programação.This model requires that you create a property for each element attribute to get and/or set its value and add it to the internal property bag of the underlying ConfigurationElement base class.

  • Modelo declarativo.Esse modelo mais simples, também chamado modelo atributo, permite que você definir um atributo de elemento usando uma propriedade e decorá-lo com atributos.Esses atributos instruem o sistema de configuração ASP.NET sobre os tipos de propriedades e seus valores padrão.Com essa informações, obtidas através de reflexão, o sistema configuração do ASP.NET cria a propriedade elemento Objetos para você e executa o exigido inicialização.

  1. The following code example shows how to use the ConfigurationProperty when creating a custom section.

// Define a custom section.
// It shows how to use the ConfigurationProperty
// class when defining a custom section
// programmatically. 
// The variables prefixed with the
// _ sign are ConfigurationProperty types.
public sealed class CustomSection :
    ConfigurationSection
{

    // CustomSection constructor.
    static CustomSection()
    {

        // Initialize the _FileName
        _FileName =
            new ConfigurationProperty("fileName",
            typeof(string), "default.txt");

        // Initialize the _MaxUsers
        _MaxUsers =
            new ConfigurationProperty("maxUsers",
            typeof(long), (long)1000,
            ConfigurationPropertyOptions.None);

        // Initialize the _MaxIdleTime
        TimeSpan minTime = TimeSpan.FromSeconds(30);
        TimeSpan maxTime = TimeSpan.FromMinutes(5);

        ConfigurationValidatorBase _TimeSpanValidator =
            new TimeSpanValidator(minTime, maxTime, false);

        _MaxIdleTime =
           new ConfigurationProperty("maxIdleTime",
       typeof(TimeSpan), TimeSpan.FromMinutes(5),
       TypeDescriptor.GetConverter(typeof(TimeSpan)),
       _TimeSpanValidator,
       ConfigurationPropertyOptions.IsRequired,
       "[Description:This is the max idle time.]");

        // Initialize the _Alias
        _Alias =
            new ConfigurationProperty("alias",
            typeof(string), "alias.txt");



        // Property collection initialization.
        // The collection (property bag) that contains 
        // the properties is declared as:
        // ConfigurationPropertyCollection _Properties;
        _Properties =
            new ConfigurationPropertyCollection();

        // The collection (property bag) that contains 
        // the properties is declared as:
        // ConfigurationPropertyCollection _Properties;
        _Properties.Add(_FileName);
        _Properties.Add(_Alias);
        _Properties.Add(_MaxUsers);
        _Properties.Add(_MaxIdleTime);

    }

    // Return the initialized property bag
    // for the configuration element.
    // The collection (property bag) that contains 
    // the properties is declared as:
    // ConfigurationPropertyCollection _Properties;
    protected override ConfigurationPropertyCollection Properties
    {
        get
        {
            return _Properties;
        }
    }


    // Clear the property.
    // It deletes all the attributes of the
    // configuration element represented by
    // the property.
    public void ClearCollection()
    {
        Properties.Clear();
    }

    // Remove an element from the property collection.
    // It deletes the specified attribute from the
    // configuration element represented by
    // the property.
    public void RemoveCollectionElement(string elName)
    {
        Properties.Remove(elName);
    }

    // Get the property collection enumerator.
    public IEnumerator GetCollectionEnumerator()
    {
        return (Properties.GetEnumerator());
    }



    [StringValidator(InvalidCharacters = " ~!@#$%^&*()[]{}/;'\"|\\",
        MinLength = 1, MaxLength = 60)]
    public string FileName
    {
        get
        {
            return (string)this["fileName"];
        }
        set
        {
            this["fileName"] = value;
        }
    }

    [StringValidator(InvalidCharacters = " ~!@#$%^&*()[]{}/;'\"|\\",
        MinLength = 1, MaxLength = 60)]
    public string Alias
    {
        get
        {
            return (string)this["alias"];
        }
        set
        {
            this["alias"] = value;
        }
    }

    [LongValidator(MinValue = 1, MaxValue = 1000000,
        ExcludeRange = false)]
    public long MaxUsers
    {
        get
        {
            return (long)this["maxUsers"];
        }
        set
        {
            this["maxUsers"] = value;
        }
    }


    public TimeSpan MaxIdleTime
    {
        get
        {
            return (TimeSpan)this["maxIdleTime"];
        }
        set
        {
            this["maxIdleTime"] = value;
        }
    }

}


A seguir está um trecho da configuração usada pelo código de exemplo acima.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="CustomSection" type="Samples.AspNet, ConfigurationProperty, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" allowDefinition="Everywhere" allowExeDefinition="MachineToApplication" restartOnExternalChanges="true" />
  </configSections>
  <CustomSection fileName="default.txt" alias="alias.txt" maxUsers="1000"
    maxIdleTime="00:05:00" />
</configuration>

O exemplo a seguir mostra como criar a seção acima.

// Create a custom section.
static void CreateSection()
{
    try
    {

        CustomSection customSection;

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

        // Create the section entry  
        // in the <configSections> and the 
        // related target section in <configuration>.
        if (config.Sections["CustomSection"] == null)
        {
            customSection = new CustomSection();
            config.Sections.Add("CustomSection", customSection);
            customSection.SectionInformation.ForceSave = true;
            config.Save(ConfigurationSaveMode.Full);
        }
    }
    catch (ConfigurationErrorsException err)
    {
        Console.WriteLine(err.ToString());
    }

}


System.Object
  System.Configuration.ConfigurationProperty
Quaisquer membros públicos estático (compartilhados na Visual Basic) desse tipo são Thread seguro. Não há garantia de que qualquer membro de instância seja isento de segmentos.
Isso foi útil para você?
(1500 caracteres restantes)

Contribuições da comunidade

ADICIONAR
A Microsoft está realizando uma pesquisa online para saber sua opinião sobre o site do MSDN. Se você optar por participar, a pesquisa online lhe será apresentada quando você sair do site do MSDN.

Deseja participar?
© 2013 Microsoft. Todos os direitos reservados.