ConfigurationProperty Klass

Definition

Representerar ett attribut eller ett underordnat till ett konfigurationselement. Det går inte att ärva den här klassen.

Detta API stöder produktinfrastrukturen och är inte avsett att användas direkt från koden.

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

Exempel

  1. I följande kodexempel visas hur du använder ConfigurationProperty när du skapar ett anpassat avsnitt.
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

Följande är ett utdrag av konfigurationsfilen som används av koden i föregående exempel.

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

I följande exempel visas hur du skapar föregående avsnitt i kod.

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

Kommentarer

När det gäller ett enkelt ConfigurationElement, till exempel det CustomSection som visas i nästa exempel, representerar objekten ConfigurationProperty attribut som fileName.

När det gäller mer komplexa konfigurationselement, till exempel ett avsnitt som innehåller underavsnitt, kan objekten authentication representera ConfigurationPropertyConfigurationElement både objekt och attribut.

Klassen ConfigurationPropertyCollection representerar samlingen av objekt som ConfigurationProperty kan vara antingen attribut eller ConfigurationElement objekt för ett konfigurationselement.

Klassen ConfigurationProperty representerar en enskild konfigurationsinställning. Med den här klassen kan du hämta eller ange namn, typ och standardvärde för en viss konfigurationsentitet (attribut eller element) och ange om attributet krävs, är en elementnyckel eller representerar en standardelementsamling.

Anteckningar till arvingar

Varje ConfigurationElement objekt skapar en intern ConfigurationPropertyCollection samling ConfigurationProperty objekt som representerar antingen elementattributen eller en samling underordnade element.

Icke-anpassningsbar information och funktioner finns i ett ElementInformation objekt som tillhandahålls av egenskapen ElementInformation .

Du kan använda en programmerings- eller deklarativ kodningsmodell (tillskriven) för att skapa ett anpassat konfigurationselement.

  • Programmeringsmodell. Den här modellen kräver att du skapar en egenskap för varje elementattribut för att hämta och/eller ange dess värde och lägga till det i den interna egenskapsuppsättningen för den underliggande ConfigurationElement basklassen.

  • Deklarativ modell. Med den här enklare modellen, även kallad attributmodell, kan du definiera ett elementattribut med hjälp av en egenskap och dekorera den med attribut. Dessa attribut instruerar ASP.NET konfigurationssystemet om egenskapstyperna och deras standardvärden. Med den här informationen, som erhålls genom reflektion, skapar ASP.NET konfigurationssystemet elementegenskapsobjekten åt dig och utför den nödvändiga initieringen.

Konstruktorer

Name Description
ConfigurationProperty(String, Type, Object, ConfigurationPropertyOptions)

Detta API stöder produktinfrastrukturen och är inte avsett att användas direkt från koden.

Initierar en ny instans av ConfigurationProperty klassen.

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

Detta API stöder produktinfrastrukturen och är inte avsett att användas direkt från koden.

Initierar en ny instans av ConfigurationProperty klassen.

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

Detta API stöder produktinfrastrukturen och är inte avsett att användas direkt från koden.

Initierar en ny instans av ConfigurationProperty klassen.

ConfigurationProperty(String, Type, Object)

Detta API stöder produktinfrastrukturen och är inte avsett att användas direkt från koden.

Initierar en ny instans av ConfigurationProperty klassen.

ConfigurationProperty(String, Type)

Detta API stöder produktinfrastrukturen och är inte avsett att användas direkt från koden.

Initierar en ny instans av ConfigurationProperty klassen.

Egenskaper

Name Description
Converter

Detta API stöder produktinfrastrukturen och är inte avsett att användas direkt från koden.

Hämtar den TypeConverter som används för att konvertera detta ConfigurationProperty till en XML-representation för att skriva till konfigurationsfilen.

DefaultValue

Detta API stöder produktinfrastrukturen och är inte avsett att användas direkt från koden.

Hämtar standardvärdet för den här ConfigurationProperty egenskapen.

Description

Detta API stöder produktinfrastrukturen och är inte avsett att användas direkt från koden.

Hämtar beskrivningen ConfigurationPropertysom är associerad med .

IsAssemblyStringTransformationRequired

Detta API stöder produktinfrastrukturen och är inte avsett att användas direkt från koden.

Anger om sammansättningsnamnet för konfigurationsegenskapen kräver transformering när det serialiseras för en tidigare version av .NET Framework.

IsDefaultCollection

Detta API stöder produktinfrastrukturen och är inte avsett att användas direkt från koden.

Hämtar ett värde som anger om egenskapen är standardsamlingen för ett element.

IsKey

Detta API stöder produktinfrastrukturen och är inte avsett att användas direkt från koden.

Hämtar ett värde som anger om det här ConfigurationProperty är nyckeln för det innehållande ConfigurationElement objektet.

IsRequired

Detta API stöder produktinfrastrukturen och är inte avsett att användas direkt från koden.

Hämtar ett värde som anger om detta ConfigurationProperty krävs.

IsTypeStringTransformationRequired

Detta API stöder produktinfrastrukturen och är inte avsett att användas direkt från koden.

Anger om typnamnet för konfigurationsegenskapen kräver transformering när det serialiseras för en tidigare version av .NET Framework.

IsVersionCheckRequired

Detta API stöder produktinfrastrukturen och är inte avsett att användas direkt från koden.

Anger om konfigurationsegenskapens överordnade konfigurationsavsnitt efterfrågas vid serialiseringstillfället för att avgöra om konfigurationsegenskapen ska serialiseras till XML.

Name

Detta API stöder produktinfrastrukturen och är inte avsett att användas direkt från koden.

Hämtar namnet på den här ConfigurationProperty.

Type

Detta API stöder produktinfrastrukturen och är inte avsett att användas direkt från koden.

Hämtar typen av det här ConfigurationProperty objektet.

Validator

Detta API stöder produktinfrastrukturen och är inte avsett att användas direkt från koden.

Hämtar , ConfigurationValidatorAttributesom används för att verifiera det här ConfigurationProperty objektet.

Metoder

Name Description
Equals(Object)

Detta API stöder produktinfrastrukturen och är inte avsett att användas direkt från koden.

Avgör om det angivna objektet är lika med det aktuella objektet.

(Ärvd från Object)
GetHashCode()

Detta API stöder produktinfrastrukturen och är inte avsett att användas direkt från koden.

Fungerar som standard-hash-funktion.

(Ärvd från Object)
GetType()

Detta API stöder produktinfrastrukturen och är inte avsett att användas direkt från koden.

Hämtar den aktuella instansen Type .

(Ärvd från Object)
MemberwiseClone()

Detta API stöder produktinfrastrukturen och är inte avsett att användas direkt från koden.

Skapar en ytlig kopia av den aktuella Object.

(Ärvd från Object)
ToString()

Detta API stöder produktinfrastrukturen och är inte avsett att användas direkt från koden.

Returnerar en sträng som representerar det aktuella objektet.

(Ärvd från Object)

Gäller för

Se även