ConfigurationElementCollection Osztály

Definíció

Gyermekelemek gyűjteményét tartalmazó konfigurációs elemet jelöl.

public ref class ConfigurationElementCollection abstract : System::Configuration::ConfigurationElement, System::Collections::ICollection
public abstract class ConfigurationElementCollection : System.Configuration.ConfigurationElement, System.Collections.ICollection
type ConfigurationElementCollection = class
    inherit ConfigurationElement
    interface ICollection
    interface IEnumerable
Public MustInherit Class ConfigurationElementCollection
Inherits ConfigurationElement
Implements ICollection
Öröklődés
ConfigurationElementCollection
Származtatott
Megvalósítás

Példák

Az alábbi példa bemutatja, hogyan használható a ConfigurationElementCollection.

Az első példa három osztályból áll: UrlsSectionés UrlsCollectionUrlConfigElement. Az UrlsSection osztály az ConfigurationCollectionAttribute egyéni konfigurációs szakasz definiálására használja. Ez a szakasz url-gyűjteményt (az UrlsCollection osztály által definiált) URL-elemeket tartalmaz (az UrlConfigElement osztály határozza meg).

using System;
using System.Configuration;

// Define a UrlsSection custom section that contains a 
// UrlsCollection collection of UrlConfigElement elements.
public class UrlsSection : ConfigurationSection
{

    // Declare the UrlsCollection collection property.
    [ConfigurationProperty("urls", IsDefaultCollection = false)]
    [ConfigurationCollection(typeof(UrlsCollection),
        AddItemName = "add",
        ClearItemsName = "clear",
        RemoveItemName = "remove")]
    public UrlsCollection Urls
    {
        get
        {
            UrlsCollection urlsCollection =
                (UrlsCollection)base["urls"];

            return urlsCollection;
        }

        set
        {
            UrlsCollection urlsCollection = value;
        }
    }

    // Create a new instance of the UrlsSection.
    // This constructor creates a configuration element 
    // using the UrlConfigElement default values.
    // It assigns this element to the collection.
    public UrlsSection()
    {
        UrlConfigElement url = new UrlConfigElement();
        Urls.Add(url);
    }
}

// Define the UrlsCollection that contains the 
// UrlsConfigElement elements.
// This class shows how to use the ConfigurationElementCollection.
public class UrlsCollection : ConfigurationElementCollection
{

    public UrlsCollection()
    {
    }

    public override ConfigurationElementCollectionType CollectionType
    {
        get
        {
            return ConfigurationElementCollectionType.AddRemoveClearMap;
        }
    }

    protected override ConfigurationElement CreateNewElement()
    {
        return new UrlConfigElement();
    }

    protected override Object GetElementKey(ConfigurationElement element)
    {
        return ((UrlConfigElement)element).Name;
    }

    public UrlConfigElement this[int index]
    {
        get
        {
            return (UrlConfigElement)BaseGet(index);
        }
        set
        {
            if (BaseGet(index) != null)
            {
                BaseRemoveAt(index);
            }
            BaseAdd(index, value);
        }
    }

    new public UrlConfigElement this[string Name]
    {
        get
        {
            return (UrlConfigElement)BaseGet(Name);
        }
    }

    public int IndexOf(UrlConfigElement url)
    {
        return BaseIndexOf(url);
    }

    public void Add(UrlConfigElement url)
    {
        BaseAdd(url);

        // Your custom code goes here.
    }

    protected override void BaseAdd(ConfigurationElement element)
    {
        BaseAdd(element, false);

        // Your custom code goes here.
    }
    
    public void Remove(UrlConfigElement url)
    {
        if (BaseIndexOf(url) >= 0)
        {
            BaseRemove(url.Name);
            // Your custom code goes here.
            Console.WriteLine("UrlsCollection: {0}", "Removed collection element!");
        }
    }
    
    public void RemoveAt(int index)
    {
        BaseRemoveAt(index);

        // Your custom code goes here.
    }
    
    public void Remove(string name)
    {
        BaseRemove(name);

        // Your custom code goes here.
    }
    
    public void Clear()
    {
        BaseClear();

        // Your custom code goes here.
        Console.WriteLine("UrlsCollection: {0}", "Removed entire collection!");
    }
}

// Define the UrlsConfigElement elements that are contained 
// by the UrlsCollection.
public class UrlConfigElement : ConfigurationElement
{
    public UrlConfigElement(String name, String url, int port)
    {
        this.Name = name;
        this.Url = url;
        this.Port = port;
    }

    public UrlConfigElement()
    {
    }

    [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)4040, 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 UrlsSection custom section that contains a 
' UrlsCollection collection of UrlConfigElement elements.
Public Class UrlsSection
    Inherits ConfigurationSection

    ' Declare the UrlsCollection collection property.
    <ConfigurationProperty("urls", IsDefaultCollection:=False), ConfigurationCollection(GetType(UrlsCollection), AddItemName:="add", ClearItemsName:="clear", RemoveItemName:="remove")>
    Public Property Urls() As UrlsCollection
        Get
            Dim urlsCollection As UrlsCollection = CType(MyBase.Item("urls"), UrlsCollection)

            Return urlsCollection
        End Get

        Set(ByVal value As UrlsCollection)
            Dim urlsCollection As UrlsCollection = value
        End Set

    End Property

    ' Create a new instance of the UrlsSection.
    ' This constructor creates a configuration element 
    ' using the UrlConfigElement default values.
    ' It assigns this element to the collection.
    Public Sub New()
        Dim url As New UrlConfigElement()
        Urls.Add(url)

    End Sub

End Class

' Define the UrlsCollection that contains the 
' UrlsConfigElement elements.
' This class shows how to use the ConfigurationElementCollection.
Public Class UrlsCollection
    Inherits System.Configuration.ConfigurationElementCollection


    Public Sub New()

    End Sub

    Public ReadOnly Property CollectionType() As ConfigurationElementCollectionType
        Get
            Return ConfigurationElementCollectionType.AddRemoveClearMap
        End Get
    End Property

    Protected Overloads Overrides Function CreateNewElement() As ConfigurationElement
        Return New UrlConfigElement()
    End Function

    Protected Overrides Function GetElementKey(ByVal element As ConfigurationElement) As Object
        Return (CType(element, UrlConfigElement)).Name
    End Function

    Default Public Shadows Property Item(ByVal index As Integer) As UrlConfigElement
        Get
            Return CType(BaseGet(index), UrlConfigElement)
        End Get
        Set(ByVal value As UrlConfigElement)
            If BaseGet(index) IsNot Nothing Then
                BaseRemoveAt(index)
            End If
            BaseAdd(value)
        End Set
    End Property

    Default Public Shadows ReadOnly Property Item(ByVal Name As String) As UrlConfigElement
        Get
            Return CType(BaseGet(Name), UrlConfigElement)
        End Get
    End Property

    Public Function IndexOf(ByVal url As UrlConfigElement) As Integer
        Return BaseIndexOf(url)
    End Function

    Public Sub Add(ByVal url As UrlConfigElement)
        BaseAdd(url)

        ' Your custom code goes here.

    End Sub

    Protected Overloads Sub BaseAdd(ByVal element As ConfigurationElement)
        BaseAdd(element, False)

        ' Your custom code goes here.

    End Sub

    Public Sub Remove(ByVal url As UrlConfigElement)
        If BaseIndexOf(url) >= 0 Then
            BaseRemove(url.Name)
            ' Your custom code goes here.
            Console.WriteLine("UrlsCollection: {0}", "Removed collection element!")
        End If
    End Sub

    Public Sub RemoveAt(ByVal index As Integer)
        BaseRemoveAt(index)

        ' Your custom code goes here.

    End Sub

    Public Sub Remove(ByVal name As String)
        BaseRemove(name)

        ' Your custom code goes here.

    End Sub

    Public Sub Clear()
        BaseClear()

        ' Your custom code goes here.
        Console.WriteLine("UrlsCollection: {0}", "Removed entire collection!")
    End Sub

End Class

' Define the UrlsConfigElement elements that are contained 
' by the UrlsCollection.
Public Class UrlConfigElement
    Inherits ConfigurationElement
    Public Sub New(ByVal name As String, ByVal url As String, ByVal port As Integer)
        Me.Name = name
        Me.Url = url
        Me.Port = port
    End Sub

    Public Sub New()

    End Sub

    <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:=CInt(4040), 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

Ez a második példakód a korábban megadott osztályokat használja. Ezt a két példát egy konzolalkalmazás-projektben kombinálhatja.

using System;
using System.Configuration;
using System.Text;

class UsingConfigurationCollectionElement
{

    // Create a custom section and save it in the 
    // application configuration file.
    static void CreateCustomSection()
    {
        try
        {

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

            // Add the custom section to the application
            // configuration file.
            UrlsSection myUrlsSection = (UrlsSection)config.Sections["MyUrls"];

            if (myUrlsSection == null)
            {
                //  The configuration file does not contain the
                // custom section yet. Create it.
                myUrlsSection = new UrlsSection();

                config.Sections.Add("MyUrls", myUrlsSection);

                // Save the application configuration file.
                myUrlsSection.SectionInformation.ForceSave = true;
                config.Save(ConfigurationSaveMode.Modified); 
            }
            else
                if (myUrlsSection.Urls.Count == 0)
                {

                    // The configuration file contains the
                    // custom section but its element collection is empty.
                    // Initialize the collection. 
                    UrlConfigElement url = new UrlConfigElement();
                    myUrlsSection.Urls.Add(url);

                    // Save the application configuration file.
                    myUrlsSection.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 myUrlsSection =
               config.GetSection("MyUrls") as UrlsSection;

            if (myUrlsSection == null)
            {
                Console.WriteLine("Failed to load UrlsSection.");
            }
            else
            {
                Console.WriteLine("Collection elements contained in the custom section collection:");
                for (int i = 0; i < myUrlsSection.Urls.Count; i++)
                {
                    Console.WriteLine("   Name={0} URL={1} Port={2}",
                        myUrlsSection.Urls[i].Name,
                        myUrlsSection.Urls[i].Url,
                        myUrlsSection.Urls[i].Port);
                }
            }
        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("ReadCustomSection(string): {0}", err.ToString());
        }
    }

    // Add an element to the custom section collection.
    // This function uses the ConfigurationCollectionElement Add method.
    static void AddCollectionElement()
    {
        try
        {

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

            // Get the custom configuration section.
            UrlsSection myUrlsSection = config.GetSection("MyUrls") as UrlsSection;

            // Add the element to the collection in the custom section.
            if (config.Sections["MyUrls"] != null)
            {
                UrlConfigElement urlElement = new UrlConfigElement();
                urlElement.Name = "Microsoft";
                urlElement.Url = "http://www.microsoft.com";
                urlElement.Port = 8080;
                
                // Use the ConfigurationCollectionElement Add method
                // to add the new element to the collection.
                myUrlsSection.Urls.Add(urlElement);

                // Save the application configuration file.
                myUrlsSection.SectionInformation.ForceSave = true;
                config.Save(ConfigurationSaveMode.Modified);

                Console.WriteLine("Added collection element to the custom section in the configuration file: {0}",
                    config.FilePath);
                Console.WriteLine();
            }
            else
            {
                Console.WriteLine("You must create the custom section first.");
            }
        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("AddCollectionElement: {0}", err.ToString());
        }
    }

    // Remove element from the custom section collection.
    // This function uses one of the ConfigurationCollectionElement 
    // overloaded Remove methods.
    static void RemoveCollectionElement()
    {
        try
        {

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

            // Get the custom configuration section.
            UrlsSection myUrlsSection = config.GetSection("MyUrls") as UrlsSection;

            // Remove the element from the custom section.
            if (config.Sections["MyUrls"] != null)
            {
                UrlConfigElement urlElement = new UrlConfigElement();
                urlElement.Name = "Microsoft";
                urlElement.Url = "http://www.microsoft.com";
                urlElement.Port = 8080;

                // Use one of the ConfigurationCollectionElement Remove 
                // overloaded methods to remove the element from the collection.
                myUrlsSection.Urls.Remove(urlElement);

                // Save the application configuration file.
                myUrlsSection.SectionInformation.ForceSave = true;
                config.Save(ConfigurationSaveMode.Full);

                Console.WriteLine("Removed collection element from he custom section in the configuration file: {0}",
                    config.FilePath);
                Console.WriteLine();
            }
            else
            {
                Console.WriteLine("You must create the custom section first.");
            }
        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("RemoveCollectionElement: {0}", err.ToString());
        }
    }

    // Remove the collection of elements from the custom section.
    // This function uses the ConfigurationCollectionElement Clear method.
    static void ClearCollectionElements()
    {
        try
        {

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

            // Get the custom configuration section.
            UrlsSection myUrlsSection = config.GetSection("MyUrls") as UrlsSection;

            // Remove the collection of elements from the section.
            if (config.Sections["MyUrls"] != null)
            {
                myUrlsSection.Urls.Clear();

                // Save the application configuration file.
                myUrlsSection.SectionInformation.ForceSave = true;
                config.Save(ConfigurationSaveMode.Full);

                Console.WriteLine("Removed collection of elements from he custom section in the configuration file: {0}",
                    config.FilePath);
                Console.WriteLine();
            }
            else
            {
                Console.WriteLine("You must create the custom section first.");
            }
        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("ClearCollectionElements: {0}", err.ToString());
        }
    }

    public static void UserMenu()
    {
        string applicationName =
           Environment.GetCommandLineArgs()[0] + ".exe";
        StringBuilder buffer = new StringBuilder();

        buffer.AppendLine("Application: " + applicationName);
        buffer.AppendLine("Make your selection.");
        buffer.AppendLine("?    -- Display help.");
        buffer.AppendLine("Q,q  -- Exit the application.");
        buffer.Append("1    -- Create a custom section that");
        buffer.AppendLine(" contains a collection of elements.");
        buffer.Append("2    -- Read the custom section that");
        buffer.AppendLine(" contains a collection of custom elements.");
        buffer.Append("3    -- Add a collection element to");
        buffer.AppendLine(" the custom section.");
        buffer.Append("4    -- Remove a collection element from");
        buffer.AppendLine(" the custom section.");
        buffer.Append("5    -- Clear the collection of elements from");
        buffer.AppendLine(" the custom section.");
        
        Console.Write(buffer.ToString());
    }

    // Obtain user's input and provide
    // feedback.
    static void Main(string[] args)
    {
        // Define user selection string.
        string selection;

        // Get the name of the application.
        string appName =
          Environment.GetCommandLineArgs()[0];

        // Get user selection.
        while (true)
        {

            UserMenu();
            Console.Write("> ");
            selection = Console.ReadLine();
            if (!string.IsNullOrEmpty(selection))
                break;
        }

        while (selection.ToLower() != "q")
        {
            // Process user's input.
            switch (selection)
            {
                case "1":
                    // Create a custom section and save it in the 
                    // application configuration file.
                    CreateCustomSection();
                    break;

                case "2":
                    // Read the custom section from the
                    // application configuration file.
                    ReadCustomSection();
                    break;

                case "3":
                    // Add a collection element to the
                    // custom section.
                    AddCollectionElement();
                    break;

                case "4":
                    // Remove a collection element from the
                    // custom section.
                    RemoveCollectionElement();
                    break;

                case "5":
                    // Clear the collection of elements from the
                    // custom section.
                    ClearCollectionElements();
                    break;

                default:
                    UserMenu();
                    break;
            }
            Console.Write("> ");
            selection = Console.ReadLine();
        }
    }
}
Imports System.Configuration
Imports System.Text

Friend Class UsingConfigurationCollectionElement

    ' Create a custom section and save it in the 
    ' application configuration file.
    Private Shared Sub CreateCustomSection()
        Try

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

            ' Add the custom section to the application
            ' configuration file.
            Dim myUrlsSection As UrlsSection = CType(config.Sections("MyUrls"), UrlsSection)

            If myUrlsSection Is Nothing Then
                '  The configuration file does not contain the
                ' custom section yet. Create it.
                myUrlsSection = New UrlsSection()

                config.Sections.Add("MyUrls", myUrlsSection)

                ' Save the application configuration file.
                myUrlsSection.SectionInformation.ForceSave = True
                config.Save(ConfigurationSaveMode.Modified)
            Else
                If myUrlsSection.Urls.Count = 0 Then

                    ' The configuration file contains the
                    ' custom section but its element collection is empty.
                    ' Initialize the collection. 
                    Dim url As New UrlConfigElement()
                    myUrlsSection.Urls.Add(url)

                    ' Save the application configuration file.
                    myUrlsSection.SectionInformation.ForceSave = True
                    config.Save(ConfigurationSaveMode.Modified)
                End If
            End If


            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 myUrlsSection As UrlsSection = TryCast(config.GetSection("MyUrls"), UrlsSection)

            If myUrlsSection Is Nothing Then
                Console.WriteLine("Failed to load UrlsSection.")
            Else
                Console.WriteLine("Collection elements contained in the custom section collection:")
                For i As Integer = 0 To myUrlsSection.Urls.Count - 1
                    Console.WriteLine("   Name={0} URL={1} Port={2}", myUrlsSection.Urls(i).Name, myUrlsSection.Urls(i).Url, myUrlsSection.Urls(i).Port)
                Next i
            End If

        Catch err As ConfigurationErrorsException
            Console.WriteLine("ReadCustomSection(string): {0}", err.ToString())
        End Try

    End Sub

    ' Add an element to the custom section collection.
    ' This function uses the ConfigurationCollectionElement Add method.
    Private Shared Sub AddCollectionElement()
        Try

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


            ' Get the custom configuration section.
            Dim myUrlsSection As UrlsSection = TryCast(config.GetSection("MyUrls"), UrlsSection)


            ' Add the element to the collection in the custom section.
            If config.Sections("MyUrls") IsNot Nothing Then
                Dim urlElement As New UrlConfigElement()
                urlElement.Name = "Microsoft"
                urlElement.Url = "http://www.microsoft.com"
                urlElement.Port = 8080

                ' Use the ConfigurationCollectionElement Add method
                ' to add the new element to the collection.
                myUrlsSection.Urls.Add(urlElement)


                ' Save the application configuration file.
                myUrlsSection.SectionInformation.ForceSave = True
                config.Save(ConfigurationSaveMode.Modified)


                Console.WriteLine("Added collection element to the custom section in the configuration file: {0}", config.FilePath)
                Console.WriteLine()
            Else
                Console.WriteLine("You must create the custom section first.")
            End If

        Catch err As ConfigurationErrorsException
            Console.WriteLine("AddCollectionElement: {0}", err.ToString())
        End Try

    End Sub

    ' Remove element from the custom section collection.
    ' This function uses one of the ConfigurationCollectionElement 
    ' overloaded Remove methods.
    Private Shared Sub RemoveCollectionElement()
        Try

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


            ' Get the custom configuration section.
            Dim myUrlsSection As UrlsSection = TryCast(config.GetSection("MyUrls"), UrlsSection)


            ' Remove the element from the custom section.
            If config.Sections("MyUrls") IsNot Nothing Then
                Dim urlElement As New UrlConfigElement()
                urlElement.Name = "Microsoft"
                urlElement.Url = "http://www.microsoft.com"
                urlElement.Port = 8080

                ' Use one of the ConfigurationCollectionElement Remove 
                ' overloaded methods to remove the element from the collection.
                myUrlsSection.Urls.Remove(urlElement)


                ' Save the application configuration file.
                myUrlsSection.SectionInformation.ForceSave = True
                config.Save(ConfigurationSaveMode.Full)


                Console.WriteLine("Removed collection element from he custom section in the configuration file: {0}", config.FilePath)
                Console.WriteLine()
            Else
                Console.WriteLine("You must create the custom section first.")
            End If

        Catch err As ConfigurationErrorsException
            Console.WriteLine("RemoveCollectionElement: {0}", err.ToString())
        End Try

    End Sub

    ' Remove the collection of elements from the custom section.
    ' This function uses the ConfigurationCollectionElement Clear method.
    Private Shared Sub ClearCollectionElements()
        Try

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


            ' Get the custom configuration section.
            Dim myUrlsSection As UrlsSection = TryCast(config.GetSection("MyUrls"), UrlsSection)


            ' Remove the collection of elements from the section.
            If config.Sections("MyUrls") IsNot Nothing Then
                myUrlsSection.Urls.Clear()


                ' Save the application configuration file.
                myUrlsSection.SectionInformation.ForceSave = True
                config.Save(ConfigurationSaveMode.Full)


                Console.WriteLine("Removed collection of elements from he custom section in the configuration file: {0}", config.FilePath)
                Console.WriteLine()
            Else
                Console.WriteLine("You must create the custom section first.")
            End If

        Catch err As ConfigurationErrorsException
            Console.WriteLine("ClearCollectionElements: {0}", err.ToString())
        End Try

    End Sub

    Public Shared Sub UserMenu()
        Dim applicationName As String = Environment.GetCommandLineArgs()(0) & ".exe"
        Dim buffer As New StringBuilder()

        buffer.AppendLine("Application: " & applicationName)
        buffer.AppendLine("Make your selection.")
        buffer.AppendLine("?    -- Display help.")
        buffer.AppendLine("Q,q  -- Exit the application.")
        buffer.Append("1    -- Create a custom section that")
        buffer.AppendLine(" contains a collection of elements.")
        buffer.Append("2    -- Read the custom section that")
        buffer.AppendLine(" contains a collection of custom elements.")
        buffer.Append("3    -- Add a collection element to")
        buffer.AppendLine(" the custom section.")
        buffer.Append("4    -- Remove a collection element from")
        buffer.AppendLine(" the custom section.")
        buffer.Append("5    -- Clear the collection of elements from")
        buffer.AppendLine(" the custom section.")

        Console.Write(buffer.ToString())
    End Sub

    ' Obtain user's input and provide
    ' feedback.
    Shared Sub Main(ByVal args() As String)
        ' Define user selection string.
        Dim selection As String

        ' Get the name of the application.
        Dim appName As String = Environment.GetCommandLineArgs()(0)

        ' Get user selection.
        Do

            UserMenu()
            Console.Write("> ")
            selection = Console.ReadLine()
            If selection <> String.Empty Then
                Exit Do
            End If
        Loop

        Do While selection.ToLower() <> "q"
            ' Process user's input.
            Select Case selection
                Case "1"
                    ' Create a custom section and save it in the 
                    ' application configuration file.
                    CreateCustomSection()

                Case "2"
                    ' Read the custom section from the
                    ' application configuration file.
                    ReadCustomSection()

                Case "3"
                    ' Add a collection element to the
                    ' custom section.
                    AddCollectionElement()

                Case "4"
                    ' Remove a collection element from the
                    ' custom section.
                    RemoveCollectionElement()

                Case "5"
                    ' Clear the collection of elements from the
                    ' custom section.
                    ClearCollectionElements()

                Case Else
                    UserMenu()
            End Select
            Console.Write("> ")
            selection = Console.ReadLine()
        Loop
    End Sub
End Class

A konzolalkalmazás futtatásakor létrejön az UrlsSection osztály egy példánya, és a következő konfigurációs elemek jönnek létre az alkalmazáskonfigurációs fájlban:

<configuration>
    <configSections>
        <section name="MyUrls" type="UrlsSection,
          ConfigurationElementCollection, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
    </configSections>
    <MyUrls>
        <urls>
           <add name="Contoso" url="http://www.contoso.com" port="4040" />
        </urls>
    </MyUrls>
</configuration

Megjegyzések

A ConfigurationElementCollection konfigurációs fájl elemeinek gyűjteménye.

Note

A konfigurációs fájlban lévő elem egy egyszerű XML-elemet vagy szakaszt jelöl. Az egyszerű elem egy XML-címke, amely kapcsolódó attribútumokkal rendelkezik, ha vannak ilyenek. Egy egyszerű elem egy szakaszt alkot. Az összetett szakaszok tartalmazhatnak egy vagy több egyszerű elemet, egy elemgyűjteményt és más szakaszokat.

Ezzel az ConfigurationElementCollection objektumgyűjteményrel ConfigurationElement dolgozhat. Ezt az osztályt úgy implementálhatja, hogy egyéni ConfigurationElement elemek gyűjteményeit adja hozzá egy ConfigurationSection.

Megjegyzések az implementálókhoz

Egyéni konfigurációelem létrehozásához programozott vagy deklaratív (attribútummal ellátott) kódolási modellt használhat.

A programozott modell megköveteli, hogy minden elemattribútumhoz létre kell hoznia egy tulajdonságot az érték lekéréséhez és beállításához, majd azt hozzá kell adnia az alapul szolgáló ConfigurationElement alaposztály belső tulajdonságcsomagjához.

A deklaratív modell, más néven az attribútumos modell lehetővé teszi egy elemattribútum definiálását egy tulajdonság használatával és attribútumokkal való konfigurálásával. Ezek az attribútumok ismertetik a ASP.NET konfigurációs rendszert a tulajdonságtípusokról és azok alapértelmezett értékeiről. ASP.NET a tükröződés segítségével lekérheti ezeket az információkat, majd létrehozhatja az elemtulajdonság-objektumokat, és végrehajthatja a szükséges inicializálást.

Konstruktorok

Name Description
ConfigurationElementCollection()

Inicializálja a ConfigurationElementCollection osztály új példányát.

ConfigurationElementCollection(IComparer)

Létrehozza az osztály új példányát ConfigurationElementCollection .

Tulajdonságok

Name Description
AddElementName

Lekéri vagy beállítja a ConfigurationElement hozzárendelni kívánt nevet a hozzáadási művelethez egy ConfigurationElementCollection származtatott osztály felülírásakor.

ClearElementName

Lekéri vagy beállítja annak a névnek a ConfigurationElement nevét, amelyet egy származtatott osztály felülírásakor a ConfigurationElementCollection tiszta művelethez szeretne társítani.

CollectionType

A típusának ConfigurationElementCollectionlekérdezése.

Count

Lekéri a gyűjtemény elemeinek számát.

CurrentConfiguration

Lekéri a legfelső szintű Configuration példányra mutató hivatkozást, amely az aktuális ConfigurationElement példány konfigurációs hierarchiáját jelöli.

(Öröklődés forrása ConfigurationElement)
ElementInformation

ElementInformation Lekéri az objektum nem testre szabható adatait és funkcióit ConfigurationElement tartalmazó objektumot.

(Öröklődés forrása ConfigurationElement)
ElementName

Lekéri a konfigurációs fájlban található elemek gyűjteményének azonosításához használt nevet, amikor felül van bírálva egy származtatott osztályban.

ElementProperty

Lekéri az ConfigurationElementProperty objektumot jelképező ConfigurationElement objektumot.

(Öröklődés forrása ConfigurationElement)
EmitClear

Lekéri vagy beállít egy értéket, amely meghatározza, hogy a gyűjtemény törölve lett-e.

EvaluationContext

Lekéri az ContextInformation objektum objektumát ConfigurationElement .

(Öröklődés forrása ConfigurationElement)
HasContext

Olyan értéket kap, amely jelzi, hogy a CurrentConfiguration tulajdonság .null

(Öröklődés forrása ConfigurationElement)
IsSynchronized

Beolvas egy értéket, amely jelzi, hogy a gyűjteményhez való hozzáférés szinkronizálva van-e.

Item[ConfigurationProperty]

Lekéri vagy beállítja ennek a konfigurációelemnek a tulajdonságát vagy attribútumát.

(Öröklődés forrása ConfigurationElement)
Item[String]

Lekéri vagy beállítja ennek a konfigurációelemnek a tulajdonságát, attribútumát vagy gyermekelemét.

(Öröklődés forrása ConfigurationElement)
LockAllAttributesExcept

Lekéri a zárolt attribútumok gyűjteményét.

(Öröklődés forrása ConfigurationElement)
LockAllElementsExcept

Lekéri a zárolt elemek gyűjteményét.

(Öröklődés forrása ConfigurationElement)
LockAttributes

Lekéri a zárolt attribútumok gyűjteményét.

(Öröklődés forrása ConfigurationElement)
LockElements

Lekéri a zárolt elemek gyűjteményét.

(Öröklődés forrása ConfigurationElement)
LockItem

Lekéri vagy beállít egy értéket, amely jelzi, hogy az elem zárolva van-e.

(Öröklődés forrása ConfigurationElement)
Properties

Lekéri a tulajdonságok gyűjteményét.

(Öröklődés forrása ConfigurationElement)
RemoveElementName

Lekéri vagy beállítja az ConfigurationElement eltávolítási művelethez társítandó nevet egy ConfigurationElementCollection származtatott osztályban felüldírált állapotban.

SyncRoot

Lekéri az objektumot, amely szinkronizálja a hozzáférését a ConfigurationElementCollection.

ThrowOnDuplicate

Beolvas egy értéket, amely jelzi, hogy egy duplikátum ConfigurationElementConfigurationElementCollection hozzáadására tett kísérlet kivételt okoz-e.

Metódusok

Name Description
BaseAdd(ConfigurationElement, Boolean)

Konfigurációs elemet ad hozzá a konfigurációelem-gyűjteményhez.

BaseAdd(ConfigurationElement)

Konfigurációs elemet ad hozzá a ConfigurationElementCollection.

BaseAdd(Int32, ConfigurationElement)

Konfigurációs elemet ad hozzá a konfigurációelem-gyűjteményhez.

BaseClear()

Eltávolítja az összes konfigurációelem-objektumot a gyűjteményből.

BaseGet(Int32)

Lekéri a konfigurációs elemet a megadott indexhelyen.

BaseGet(Object)

A megadott kulccsal rendelkező konfigurációs elemet adja vissza.

BaseGetAllKeys()

A kulcsok tömbjét adja vissza a fájlban ConfigurationElementCollectiontalálható összes konfigurációs elemhez.

BaseGetKey(Int32)

Lekéri a megadott indexhely kulcsát ConfigurationElement .

BaseIndexOf(ConfigurationElement)

A megadott ConfigurationElementindexet jelzi.

BaseIsRemoved(Object)

Azt jelzi, hogy a ConfigurationElement megadott kulccsal rendelkező kulcs el lett-e távolítva a ConfigurationElementCollectionprogramból.

BaseRemove(Object)

Eltávolít egy ConfigurationElement elemet a gyűjteményből.

BaseRemoveAt(Int32)

Eltávolítja a ConfigurationElement megadott indexhelyet.

CopyTo(ConfigurationElement[], Int32)

A tömb tartalmát ConfigurationElementCollection átmásolja egy tömbbe.

CreateNewElement()

Ha felül van bírálva egy származtatott osztályban, létrehoz egy újat ConfigurationElement.

CreateNewElement(String)

Létrehoz egy újat ConfigurationElement , ha felül van bírálva egy származtatott osztályban.

DeserializeElement(XmlReader, Boolean)

Beolvassa az XML-t a konfigurációs fájlból.

(Öröklődés forrása ConfigurationElement)
Equals(Object)

Összehasonlítja a ConfigurationElementCollection megadott objektumot.

GetElementKey(ConfigurationElement)

Lekéri egy adott konfigurációelem elemkulcsát, ha felül van bírálva egy származtatott osztályban.

GetEnumerator()

IEnumerator A a .-on keresztüli iteráláshoz használt parancsot ConfigurationElementCollectionkap.

GetHashCode()

A példányt jelképező ConfigurationElementCollection egyedi értéket kap.

GetTransformedAssemblyString(String)

A megadott szerelvénynév átalakított verzióját adja vissza.

(Öröklődés forrása ConfigurationElement)
GetTransformedTypeString(String)

A megadott típusnév átalakított verzióját adja vissza.

(Öröklődés forrása ConfigurationElement)
GetType()

Lekéri az Type aktuális példányt.

(Öröklődés forrása Object)
Init()

Beállítja az ConfigurationElement objektumot a kezdeti állapotára.

(Öröklődés forrása ConfigurationElement)
InitializeDefault()

Az objektum alapértelmezett értékkészletének inicializálására ConfigurationElement szolgál.

(Öröklődés forrása ConfigurationElement)
IsElementName(String)

Azt jelzi, hogy a megadott ConfigurationElement létezik-e a ConfigurationElementCollection.

IsElementRemovable(ConfigurationElement)

Azt jelzi, hogy a megadott ConfigurationElement fájl eltávolítható-e a ConfigurationElementCollectionprogramból.

IsModified()

Azt jelzi, hogy ez ConfigurationElementCollection módosult-e a legutóbbi mentés vagy betöltés óta, amikor felül van bírálva egy származtatott osztályban.

IsReadOnly()

Azt jelzi, hogy az ConfigurationElementCollection objektum csak olvasható-e.

ListErrors(IList)

Hozzáadja az objektumban és az összes alelemben található ConfigurationElement érvénytelen tulajdonsághibákat az átadott listához.

(Öröklődés forrása ConfigurationElement)
MemberwiseClone()

Az aktuális Objectpéldány sekély másolatát hozza létre.

(Öröklődés forrása Object)
OnDeserializeUnrecognizedAttribute(String, String)

Beolvas egy értéket, amely jelzi, hogy a deszerializálás során ismeretlen attribútumot észleltek-e.

(Öröklődés forrása ConfigurationElement)
OnDeserializeUnrecognizedElement(String, XmlReader)

A konfigurációs rendszer kivételt okoz.

OnRequiredPropertyNotFound(String)

Kivételt eredményez, ha a szükséges tulajdonság nem található.

(Öröklődés forrása ConfigurationElement)
PostDeserialize()

A deszerializálás után hívjuk.

(Öröklődés forrása ConfigurationElement)
PreSerialize(XmlWriter)

A szerializálás előtt hívjuk meg.

(Öröklődés forrása ConfigurationElement)
Reset(ConfigurationElement)

Visszaállítja a ConfigurationElementCollection nem módosított állapotot, ha felül van bírálva egy származtatott osztályban.

ResetModified()

Visszaállítja IsModified() a tulajdonság false értékét, amikor felül van bírálva egy származtatott osztályban.

SerializeElement(XmlWriter, Boolean)

A konfigurációs adatokat a konfigurációs fájl XML-elemére írja, amikor felül van bírálva egy származtatott osztályban.

SerializeToXmlElement(XmlWriter, String)

A konfigurációelem külső címkéit a konfigurációs fájlba írja, amikor egy származtatott osztályban implementálják.

(Öröklődés forrása ConfigurationElement)
SetPropertyValue(ConfigurationProperty, Object, Boolean)

Beállít egy tulajdonságot a megadott értékre.

(Öröklődés forrása ConfigurationElement)
SetReadOnly()

Beállítja az IsReadOnly() objektum és az ConfigurationElementCollection összes alelem tulajdonságát.

ToString()

Az aktuális objektumot jelképező sztringet ad vissza.

(Öröklődés forrása Object)
Unmerge(ConfigurationElement, ConfigurationElement, ConfigurationSaveMode)

Megfordítja a konfigurációs információknak a konfigurációs hierarchia különböző szintjeiről való egyesítésének hatását.

Explicit interfész-implementációk

Name Description
ICollection.CopyTo(Array, Int32)

Másolja a ConfigurationElementCollection tömbbe.

Bővítő metódusok

Name Description
AsParallel(IEnumerable)

Lehetővé teszi a lekérdezés párhuzamosítását.

AsQueryable(IEnumerable)

Átalakítja az egyiket IEnumerableIQueryable.

Cast<TResult>(IEnumerable)

Egy elem elemeit IEnumerable a megadott típusra veti.

OfType<TResult>(IEnumerable)

Egy adott típus alapján szűri IEnumerable egy adott elem elemeit.

A következőre érvényes:

Lásd még