ConfigurationPropertyAttribute Klasa

Definicja

Deklaratywnie nakazuje platformie .NET utworzenie wystąpienia właściwości konfiguracji. Klasa ta nie może być dziedziczona.

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
Dziedziczenie
ConfigurationPropertyAttribute
Atrybuty

Przykłady

W poniższym przykładzie pokazano, jak zdefiniować właściwości obiektu niestandardowego ConfigurationSection przy użyciu atrybutu ConfigurationPropertyAttribute .

Przykład zawiera dwie klasy. Klasa niestandardowa UrlsSection używa klasy , ConfigurationPropertyAttribute aby zdefiniować własne właściwości. Klasa UsingConfigurationPropertyAttribute używa elementu , UrlsSection aby odczytać i zapisać sekcję niestandardową w pliku konfiguracji aplikacji.

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

Poniżej znajduje się fragment pliku konfiguracji zawierającego sekcję niestandardową, zgodnie z definicją w poprzednim przykładzie.

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

Uwagi

Element służy ConfigurationPropertyAttribute do dekorowania właściwości konfiguracji, co spowoduje, że platforma .NET utworzy wystąpienie i zainicjuje właściwość przy użyciu wartości parametru dekorowania.

Uwaga

Najprostszym sposobem utworzenia niestandardowego elementu konfiguracji jest użycie modelu przypisanego (deklaratywnego). Deklarujesz niestandardowe właściwości publiczne i dekorujesz je atrybutem ConfigurationPropertyAttribute . Dla każdej właściwości oznaczonej tym atrybutem platforma .NET używa odbicia w celu odczytania parametrów dekorowania i utworzenia powiązanego ConfigurationProperty wystąpienia. Możesz również użyć modelu programowego. W tym przypadku twoim obowiązkiem jest zadeklarowanie niestandardowych właściwości publicznych i zwrócenie ich kolekcji.

System konfiguracji platformy .NET udostępnia typy atrybutów, których można użyć podczas tworzenia niestandardowych elementów konfiguracji. Istnieją dwa rodzaje atrybutów:

  1. Typy instruujące platformę .NET, jak utworzyć wystąpienie niestandardowych właściwości elementu-konfiguracji. Te typy obejmują:

  2. Typy instruujące platformę .NET, jak zweryfikować niestandardowe właściwości elementu konfiguracji. Te typy obejmują:

Konstruktory

ConfigurationPropertyAttribute(String)

Inicjuje nowe wystąpienie klasy ConfigurationPropertyAttribute.

Właściwości

DefaultValue

Pobiera lub ustawia wartość domyślną właściwości ozdobionej.

IsDefaultCollection

Pobiera lub ustawia wartość wskazującą, czy jest to domyślna kolekcja właściwości dla właściwości konfiguracji ozdobionej.

IsKey

Pobiera lub ustawia wartość wskazującą, czy jest to właściwość klucza właściwości elementu ozdobionego.

IsRequired

Pobiera lub ustawia wartość wskazującą, czy właściwość elementu ozdobionego jest wymagana.

Name

Pobiera nazwę dekorowanej właściwości configuration-element.

Options

Pobiera lub ustawia ConfigurationPropertyOptions dla dekorowanej właściwości configuration-element.

TypeId

Po zaimplementowaniu w klasie pochodnej pobiera unikatowy identyfikator dla tego Attributeelementu .

(Odziedziczone po Attribute)

Metody

Equals(Object)

Zwraca wartość wskazującą, czy to wystąpienie jest równe podanemu obiektowi.

(Odziedziczone po Attribute)
GetHashCode()

Zwraca wartość skrótu dla tego wystąpienia.

(Odziedziczone po Attribute)
GetType()

Type Pobiera wartość bieżącego wystąpienia.

(Odziedziczone po Object)
IsDefaultAttribute()

Podczas zastępowania w klasie pochodnej wskazuje, czy wartość tego wystąpienia jest wartością domyślną dla klasy pochodnej.

(Odziedziczone po Attribute)
Match(Object)

Po przesłonięciu w klasie pochodnej zwraca wartość wskazującą, czy to wystąpienie jest równe określonemu obiektowi.

(Odziedziczone po Attribute)
MemberwiseClone()

Tworzy płytkią kopię bieżącego Objectelementu .

(Odziedziczone po Object)
ToString()

Zwraca ciąg reprezentujący bieżący obiekt.

(Odziedziczone po Object)

Jawne implementacje interfejsu

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

Zestaw nazw jest mapowany na odpowiedni zestaw identyfikatorów wysyłania.

(Odziedziczone po Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Pobiera informacje o typie dla obiektu, który może służyć do pobierania informacji o typie dla interfejsu.

(Odziedziczone po Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Pobiera informację o liczbie typów interfejsów, jakie zawiera obiekt (0 lub 1).

(Odziedziczone po Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Umożliwia dostęp do właściwości i metod udostępnianych przez obiekt.

(Odziedziczone po Attribute)

Dotyczy

Zobacz też