ConfigurationProperty Klasa

Definicja

Reprezentuje atrybut lub element podrzędny elementu konfiguracji. Klasa ta nie może być dziedziczona.

Ten interfejs API obsługuje infrastrukturę produktu i nie jest przeznaczony do użycia bezpośrednio z poziomu kodu.

public ref class ConfigurationProperty sealed
public sealed class ConfigurationProperty
type ConfigurationProperty = class
Public NotInheritable Class ConfigurationProperty
Dziedziczenie
ConfigurationProperty

Przykłady

  1. W poniższym przykładzie kodu pokazano, jak używać ConfigurationProperty sekcji podczas tworzenia sekcji niestandardowej.
using System;
using System.Configuration;
using System.Collections;
using System.ComponentModel;

namespace ConfigurationPropertyExample
{
    // Define a custom section.
    // Shows how to use the ConfigurationProperty
    // class when defining a custom section.
    public sealed class CustomSection : ConfigurationSection
    {
        // The collection (property bag) that contains 
        // the section properties.
        private static ConfigurationPropertyCollection _Properties;

        // The FileName property.
        private static ConfigurationProperty _FileName;

        // The Alias property.
        private static ConfigurationProperty _Alias;

        // The MaxUsers property.
        private static ConfigurationProperty _MaxUsers;

        // The MaxIdleTime property.
        private static ConfigurationProperty _MaxIdleTime;

        // CustomSection constructor.
        static CustomSection()
        {
            // Initialize the _FileName property
            _FileName =
                new ConfigurationProperty("fileName",
                typeof(string), "default.txt");

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

            // Initialize the _MaxIdleTime property
            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 property
            _Alias =
                new ConfigurationProperty("alias",
                typeof(string), "alias.txt");

            // Initialize the Property collection.
            _Properties = new ConfigurationPropertyCollection();
            _Properties.Add(_FileName);
            _Properties.Add(_Alias);
            _Properties.Add(_MaxUsers);
            _Properties.Add(_MaxIdleTime);
        }

        // Return the initialized property bag
        // for the configuration element.
        protected override ConfigurationPropertyCollection Properties
        {
            get
            {
                return _Properties;
            }
        }

        // Clear the property.
        public void ClearCollection()
        {
            Properties.Clear();
        }

        // Remove an element from the property collection.
        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;
            }
        }
    }
}
Imports System.Configuration
Imports System.Collections
Imports System.ComponentModel

' Define a custom section.
' Shows how to use the ConfigurationProperty
' class when defining a custom section.
Public NotInheritable Class CustomSection
    Inherits ConfigurationSection

    ' The collection (property bag) that contains 
    ' the section properties.
    Private Shared _Properties As ConfigurationPropertyCollection

    ' The FileName property.
    Private Shared _FileName As ConfigurationProperty

    ' The Alias property.
    Private Shared _Alias As ConfigurationProperty

    ' The MasUsers property.
    Private Shared _MaxUsers As ConfigurationProperty

    ' The MaxIdleTime property.
    Private Shared _MaxIdleTime As ConfigurationProperty

    ' CustomSection constructor.
    Shared Sub New()

        ' Initialize the _FileName property
        _FileName = New ConfigurationProperty( _
            "fileName", GetType(String), "default.txt")

        ' Initialize the _MaxUsers property
        _MaxUsers = New ConfigurationProperty( _
            "maxUsers", GetType(Long), 1000L, _
            ConfigurationPropertyOptions.None)

        ' Initialize the _MaxIdleTime property
        Dim minTime As TimeSpan = TimeSpan.FromSeconds(30)
        Dim maxTime As TimeSpan = TimeSpan.FromMinutes(5)
        Dim _TimeSpanValidator = _
            New TimeSpanValidator(minTime, maxTime, False)

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

        ' Initialize the _Alias property
        _Alias = New ConfigurationProperty( _
            "alias", GetType(String), "alias.txt")

        ' Property collection initialization.
        ' The collection (property bag) that contains 
        ' the properties is declared as:
        ' ConfigurationPropertyCollection _Properties;
        _Properties = New ConfigurationPropertyCollection()
        _Properties.Add(_FileName)
        _Properties.Add(_Alias)
        _Properties.Add(_MaxUsers)
        _Properties.Add(_MaxIdleTime)

    End Sub

    ' Return the initialized property bag
    ' for the configuration element.
    Protected Overrides ReadOnly Property Properties() _
    As ConfigurationPropertyCollection
        Get
            Return _Properties
        End Get
    End Property

    <StringValidator(InvalidCharacters:= _
    " ~!@#$%^&*()[]{}/;'""|\", MinLength:=1, _
    MaxLength:=60)> _
    Public Property FileName() As String
        Get
            Return CStr(Me("fileName"))
        End Get
        Set(ByVal value As String)
            Me("fileName") = value
        End Set
    End Property

    <StringValidator(InvalidCharacters:= _
    " ~!@#$%^&*()[]{}/;'""|\", MinLength:=1, _
    MaxLength:=60)> _
    Public Property [Alias]() As String
        Get
            Return CStr(Me("alias"))
        End Get
        Set(ByVal value As String)
            Me("alias") = value
        End Set
    End Property

    <LongValidator(MinValue:=1, _
    MaxValue:=1000000, ExcludeRange:=False)> _
    Public Property MaxUsers() As Long
        Get
            Return Fix(Me("maxUsers"))
        End Get
        Set(ByVal value As Long)
            Me("maxUsers") = value
        End Set
    End Property

    Public Property MaxIdleTime() As TimeSpan
        Get
            Return CType(Me("maxIdleTime"), TimeSpan)
        End Get
        Set(ByVal value As TimeSpan)
            Me("maxIdleTime") = value
        End Set
    End Property
End Class

Poniżej przedstawiono fragment pliku konfiguracji używanego przez kod w poprzednim przykładzie.

<configuration>
  <configSections>
    <section name="CustomSection" type="ConfigurationPropertyExample.CustomSection, ConfigurationPropertyExample"
      allowDefinition="Everywhere" allowExeDefinition="MachineToApplication"
      restartOnExternalChanges="true" />
  </configSections>
  <CustomSection fileName="override.txt" alias="alias.txt"
    maxUsers="1000" maxIdleTime="00:05:00" />
</configuration>

W poniższym przykładzie pokazano, jak utworzyć poprzednią sekcję w kodzie.

// Define a custom section programmatically.
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>.
        // Call it "CustomSection2" since the file in this 
        // example already has "CustomSection".
        if (config.Sections["CustomSection"] == null)
        {
            customSection = new CustomSection();
            config.Sections.Add("CustomSection2", customSection);
            customSection.SectionInformation.ForceSave = true;
            config.Save(ConfigurationSaveMode.Full);
        }
    }
    catch (ConfigurationErrorsException err)
    {
        Console.WriteLine(err.ToString());
    }
}
' Create a custom section.
Shared Sub CreateSection()
    Try
        Dim customSection As CustomSection

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

        ' Create the section entry  
        ' in the <configSections> and the 
        ' related target section in <configuration>.
        ' Since the config file already has "CustomSection",
        ' call this one "CustomSection2".
        If config.Sections("CustomSection") Is Nothing Then
            customSection = New CustomSection()
            config.Sections.Add("CustomSection", customSection)
            customSection.SectionInformation.ForceSave = True
            config.Save(ConfigurationSaveMode.Full)
        End If
    Catch err As ConfigurationErrorsException
        Console.WriteLine(err.ToString())
    End Try
End Sub

Uwagi

W przypadku prostego ConfigurationElementelementu , takiego jak pokazany CustomSection w następnym przykładzie, ConfigurationProperty obiekty reprezentują atrybuty, takie jak fileName.

W przypadku bardziej złożonych elementów konfiguracji, takich jak sekcja zawierająca podsekcje, na przykład authenticationConfigurationProperty obiekty mogą reprezentować ConfigurationElement obiekty, a także atrybuty.

Klasa ConfigurationPropertyCollection reprezentuje kolekcję ConfigurationProperty obiektów, które mogą być atrybutami lub ConfigurationElement obiektami elementu konfiguracji.

Klasa ConfigurationProperty reprezentuje indywidualne ustawienie konfiguracji. Ta klasa umożliwia pobranie lub ustawienie nazwy, typu i wartości domyślnej dla określonej jednostki konfiguracji (atrybutu lub elementu) i określenie, czy atrybut jest wymagany, jest kluczem elementu lub reprezentuje domyślną kolekcję elementów.

Uwagi dotyczące dziedziczenia

Każdy ConfigurationElement obiekt tworzy wewnętrzną ConfigurationPropertyCollection kolekcję ConfigurationProperty obiektów, która reprezentuje atrybuty elementu lub kolekcję elementów podrzędnych.

Informacje i funkcje nie dostosowywalne są zawarte przez ElementInformation obiekt udostępniany przez ElementInformation właściwość.

Do utworzenia niestandardowego elementu konfiguracji można użyć modelu programowego lub deklaratywnego (przypisanego).

  • Model programowy. Ten model wymaga utworzenia właściwości dla każdego atrybutu elementu w celu pobrania i/lub ustawienia jego wartości i dodania jej do wewnętrznej torby właściwości bazowej ConfigurationElement klasy bazowej.

  • Model deklaratywny. Ten prostszy model, nazywany również modelem przypisanym, umożliwia definiowanie atrybutu elementu przy użyciu właściwości i dekorowanie go atrybutami. Te atrybuty instruują system konfiguracji ASP.NET o typach właściwości i ich wartościach domyślnych. Dzięki tym informacjom uzyskanym przez odbicie system konfiguracji ASP.NET tworzy obiekty właściwości elementu i wykonuje wymaganą inicjację.

Konstruktory

ConfigurationProperty(String, Type)

Ten interfejs API obsługuje infrastrukturę produktu i nie jest przeznaczony do użycia bezpośrednio z poziomu kodu.

Inicjuje nowe wystąpienie klasy ConfigurationProperty.

ConfigurationProperty(String, Type, Object)

Ten interfejs API obsługuje infrastrukturę produktu i nie jest przeznaczony do użycia bezpośrednio z poziomu kodu.

Inicjuje nowe wystąpienie klasy ConfigurationProperty.

ConfigurationProperty(String, Type, Object, ConfigurationPropertyOptions)

Ten interfejs API obsługuje infrastrukturę produktu i nie jest przeznaczony do użycia bezpośrednio z poziomu kodu.

Inicjuje nowe wystąpienie klasy ConfigurationProperty.

ConfigurationProperty(String, Type, Object, TypeConverter, ConfigurationValidatorBase, ConfigurationPropertyOptions)

Ten interfejs API obsługuje infrastrukturę produktu i nie jest przeznaczony do użycia bezpośrednio z poziomu kodu.

Inicjuje nowe wystąpienie klasy ConfigurationProperty.

ConfigurationProperty(String, Type, Object, TypeConverter, ConfigurationValidatorBase, ConfigurationPropertyOptions, String)

Ten interfejs API obsługuje infrastrukturę produktu i nie jest przeznaczony do użycia bezpośrednio z poziomu kodu.

Inicjuje nowe wystąpienie klasy ConfigurationProperty.

Właściwości

Converter

Ten interfejs API obsługuje infrastrukturę produktu i nie jest przeznaczony do użycia bezpośrednio z poziomu kodu.

Pobiera element TypeConverter służący do konwertowania go ConfigurationProperty na reprezentację XML do zapisywania w pliku konfiguracji.

DefaultValue

Ten interfejs API obsługuje infrastrukturę produktu i nie jest przeznaczony do użycia bezpośrednio z poziomu kodu.

Pobiera wartość domyślną dla tej ConfigurationProperty właściwości.

Description

Ten interfejs API obsługuje infrastrukturę produktu i nie jest przeznaczony do użycia bezpośrednio z poziomu kodu.

Pobiera opis skojarzony z elementem ConfigurationProperty.

IsAssemblyStringTransformationRequired

Ten interfejs API obsługuje infrastrukturę produktu i nie jest przeznaczony do użycia bezpośrednio z poziomu kodu.

Wskazuje, czy nazwa zestawu dla właściwości konfiguracji wymaga przekształcenia w przypadku serializacji dla wcześniejszej wersji .NET Framework.

IsDefaultCollection

Ten interfejs API obsługuje infrastrukturę produktu i nie jest przeznaczony do użycia bezpośrednio z poziomu kodu.

Pobiera wartość wskazującą, czy właściwość jest domyślną kolekcją elementu.

IsKey

Ten interfejs API obsługuje infrastrukturę produktu i nie jest przeznaczony do użycia bezpośrednio z poziomu kodu.

Pobiera wartość wskazującą, czy jest to ConfigurationProperty klucz dla obiektu zawierającego ConfigurationElement .

IsRequired

Ten interfejs API obsługuje infrastrukturę produktu i nie jest przeznaczony do użycia bezpośrednio z poziomu kodu.

Pobiera wartość wskazującą, czy jest to ConfigurationProperty wymagane.

IsTypeStringTransformationRequired

Ten interfejs API obsługuje infrastrukturę produktu i nie jest przeznaczony do użycia bezpośrednio z poziomu kodu.

Wskazuje, czy nazwa typu właściwości konfiguracji wymaga przekształcenia w przypadku serializacji dla wcześniejszej wersji .NET Framework.

IsVersionCheckRequired

Ten interfejs API obsługuje infrastrukturę produktu i nie jest przeznaczony do użycia bezpośrednio z poziomu kodu.

Wskazuje, czy sekcja konfiguracji nadrzędnej właściwości konfiguracji jest odpytywane w czasie serializacji, aby określić, czy właściwość konfiguracji powinna być serializowana w formacie XML.

Name

Ten interfejs API obsługuje infrastrukturę produktu i nie jest przeznaczony do użycia bezpośrednio z poziomu kodu.

Pobiera nazwę tego ConfigurationPropertyelementu .

Type

Ten interfejs API obsługuje infrastrukturę produktu i nie jest przeznaczony do użycia bezpośrednio z poziomu kodu.

Pobiera typ tego ConfigurationProperty obiektu.

Validator

Ten interfejs API obsługuje infrastrukturę produktu i nie jest przeznaczony do użycia bezpośrednio z poziomu kodu.

Pobiera obiekt ConfigurationValidatorAttribute, który służy do sprawdzania poprawności tego ConfigurationProperty obiektu.

Metody

Equals(Object)

Ten interfejs API obsługuje infrastrukturę produktu i nie jest przeznaczony do użycia bezpośrednio z poziomu kodu.

Określa, czy dany obiekt jest taki sam, jak bieżący obiekt.

(Odziedziczone po Object)
GetHashCode()

Ten interfejs API obsługuje infrastrukturę produktu i nie jest przeznaczony do użycia bezpośrednio z poziomu kodu.

Służy jako domyślna funkcja skrótu.

(Odziedziczone po Object)
GetType()

Ten interfejs API obsługuje infrastrukturę produktu i nie jest przeznaczony do użycia bezpośrednio z poziomu kodu.

Type Pobiera bieżące wystąpienie.

(Odziedziczone po Object)
MemberwiseClone()

Ten interfejs API obsługuje infrastrukturę produktu i nie jest przeznaczony do użycia bezpośrednio z poziomu kodu.

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

(Odziedziczone po Object)
ToString()

Ten interfejs API obsługuje infrastrukturę produktu i nie jest przeznaczony do użycia bezpośrednio z poziomu kodu.

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

(Odziedziczone po Object)

Dotyczy

Zobacz też