ConfigurationCollectionAttribute Klasse

Definition

Weist .NET deklarativ an, eine Instanz einer Sammlung von Konfigurationselementen zu erstellen. Diese Klasse kann nicht vererbt werden.

public ref class ConfigurationCollectionAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Property)]
public sealed class ConfigurationCollectionAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Property)>]
type ConfigurationCollectionAttribute = class
    inherit Attribute
Public NotInheritable Class ConfigurationCollectionAttribute
Inherits Attribute
Vererbung
ConfigurationCollectionAttribute
Attribute

Beispiele

Im folgenden Beispiel wird gezeigt, wie sie verwendet werden ConfigurationCollectionAttribute.

Dieses Beispiel besteht aus drei Klassen: UrlsSection, UrlsCollectionund UrlConfigElement. Die UrlsSection -Klasse verwendet den ConfigurationCollectionAttribute , um einen benutzerdefinierten Konfigurationsabschnitt zu definieren. Dieser Abschnitt enthält eine URL-Auflistung (definiert durch die UrlsCollection -Klasse) von URL-Elementen (definiert durch die UrlConfigElement -Klasse). Wenn Sie das Beispiel ausführen, wird eine Instanz der UrlsSection -Klasse erstellt, und die folgenden Konfigurationselemente werden in der Anwendungskonfigurationsdatei generiert:

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

using System;
using System.Configuration;

// Define a custom section that contains a custom
// UrlsCollection collection of custom UrlConfigElement elements.
// This class shows how to use the ConfigurationCollectionAttribute.
public class UrlsSection : ConfigurationSection
{
    // Declare the Urls collection property using the
    // ConfigurationCollectionAttribute.
    // This allows to build a nested section that contains
    // a collection of elements.
    [ConfigurationProperty("urls", IsDefaultCollection = false)]
    [ConfigurationCollection(typeof(UrlsCollection),
        AddItemName = "add",
        ClearItemsName = "clear",
        RemoveItemName = "remove")]
    public UrlsCollection Urls
    {
        get
        {
            UrlsCollection urlsCollection =
                (UrlsCollection)base["urls"];
            return urlsCollection;
        }
    }
}

// Define the custom UrlsCollection that contains the 
// custom UrlsConfigElement elements.
public class UrlsCollection : ConfigurationElementCollection
{
    public UrlsCollection()
    {
        UrlConfigElement url = (UrlConfigElement)CreateNewElement();
        Add(url);
    }

    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);
    }
    protected override void BaseAdd(ConfigurationElement element)
    {
        BaseAdd(element, false);
    }

    public void Remove(UrlConfigElement url)
    {
        if (BaseIndexOf(url) >= 0)
            BaseRemove(url.Name);
    }

    public void RemoveAt(int index)
    {
        BaseRemoveAt(index);
    }

    public void Remove(string name)
    {
        BaseRemove(name);
    }

    public void Clear()
    {
        BaseClear();
    }
}

// Define the custom UrlsConfigElement elements that are contained 
// by the custom UrlsCollection.
// Notice that you can change the default values to create new default elements.
public class UrlConfigElement : ConfigurationElement
{
    public UrlConfigElement(String name, String url)
    {
        this.Name = name;
        this.Url = url;
    }

    public UrlConfigElement()
    {

        this.Name = "Contoso";
        this.Url = "http://www.contoso.com";
        this.Port = 0;
    }

    [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 that contains a custom
' UrlsCollection collection of custom UrlConfigElement elements.
' This class shows how to use the ConfigurationCollectionAttribute.
Public Class UrlsSection
    Inherits ConfigurationSection
    ' Declare the Urls collection property using the
    ' ConfigurationCollectionAttribute.
    ' This allows to build a nested section that contains
    ' a collection of elements.
    <ConfigurationProperty("urls", IsDefaultCollection:=False),
        System.Configuration.ConfigurationCollection(GetType(UrlsCollection),
        AddItemName:="add", ClearItemsName:="clear", RemoveItemName:="remove")> _
    Public ReadOnly Property Urls() As UrlsCollection
        Get
            Dim urlsCollection As UrlsCollection = CType(MyBase.Item("urls"), UrlsCollection)
            Return urlsCollection
        End Get
    End Property

End Class

' Define the custom UrlsCollection that contains the 
' custom UrlsConfigElement elements.
Public Class UrlsCollection
    Inherits ConfigurationElementCollection
    Public Sub New()
        Dim url As UrlConfigElement = CType(CreateNewElement(), UrlConfigElement)
        Add(url)
    End Sub

    Public Overrides 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 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(index, 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)
    End Sub
    Protected Overloads Overrides Sub BaseAdd(ByVal element As ConfigurationElement)
        BaseAdd(element, False)
    End Sub

    Public Sub Remove(ByVal url As UrlConfigElement)
        If BaseIndexOf(url) >= 0 Then
            BaseRemove(url.Name)
        End If
    End Sub

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

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

    Public Sub Clear()
        BaseClear()
    End Sub
End Class

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

    Public Sub New()
        Me.Name = "Contoso"
        Me.Url = "http://www.contoso.com"
        Me.Port = 0
    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:=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;

class UsingConfigurationCollectionAttribute
{

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

            // Create a custom configuration section.
            UrlsSection myUrlsSection = 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["MyUrls"] == null)
            {
                config.Sections.Add("MyUrls", myUrlsSection);
            }

            // 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 =
               ConfigurationManager.GetSection("MyUrls") as UrlsSection;

            if (myUrlsSection == null)
            {
                Console.WriteLine("Failed to load UrlsSection.");
            }
            else
            {
                Console.WriteLine("URLs defined in the configuration file:");
                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());
        }
    }
    
    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();
        Console.WriteLine("Enter any key to exit.");

        Console.ReadLine();
    }
}
Imports System.Configuration


Friend Class UsingConfigurationCollectionAttribute

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

            ' Create a custom configuration section.
            Dim myUrlsSection 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("MyUrls") Is Nothing Then
                config.Sections.Add("MyUrls", myUrlsSection)
            End If


            ' 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 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(ConfigurationManager.GetSection("MyUrls"), UrlsSection)

            If myUrlsSection Is Nothing Then
                Console.WriteLine("Failed to load UrlsSection.")
            Else
                Console.WriteLine("URLs defined in app.config:")
                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

    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()
        Console.WriteLine("Enter any key to exit.")

        Console.ReadLine()
    End Sub
End Class

Hinweise

Sie verwenden das ConfigurationCollectionAttribute -Attribut, um ein ConfigurationElementCollection Element zu dekorieren. Dadurch wird .NET angewiesen, eine Instanz der Auflistung zu erstellen und sie mit Ihren benutzerdefinierten ConfigurationElement Werten zu initialisieren.

Hinweis

Die einfachste Möglichkeit zum Erstellen eines benutzerdefinierten Konfigurationselements ist die Verwendung des attributierten (deklarativen) Modells. Sie deklarieren die Elemente und dekorieren sie mit dem ConfigurationCollectionAttribute -Attribut. Für jedes Element, das mit diesem Attribut gekennzeichnet ist, verwendet .NET Reflektion, um die Dekorierungsparameter zu lesen und eine zugehörige ConfigurationElementCollection Instanz zu erstellen. Sie können auch das programmgesteuerte Modell verwenden. In diesem Fall liegt es in Ihrer Verantwortung, die benutzerdefinierte öffentliche Auflistung zu deklarieren, aber auch den ConfigurationElementCollection Member zu überschreiben und die Eigenschaftenauflistung zurückzugeben.

Das .NET-Konfigurationssystem stellt Attributtypen bereit, die Sie beim Erstellen benutzerdefinierter Konfigurationselemente verwenden können. Es gibt zwei Arten von Attributen:

Konstruktoren

ConfigurationCollectionAttribute(Type)

Initialisiert eine neue Instanz der ConfigurationCollectionAttribute-Klasse.

Eigenschaften

AddItemName

Ruft den Namen des <add>-Konfigurationselements ab oder legt diesen fest.

ClearItemsName

Ruft den Namen des <clear>-Konfigurationselements ab oder legt diesen fest.

CollectionType

Ruft den Typ des ConfigurationCollectionAttribute-Attributs ab oder legt diesen fest.

ItemType

Ruft den Typ des Auflistungselements ab.

RemoveItemName

Ruft den Namen des <remove>-Konfigurationselements ab oder legt diesen fest.

TypeId

Ruft bei Implementierung in einer abgeleiteten Klasse einen eindeutigen Bezeichner für dieses Attribute ab.

(Geerbt von Attribute)

Methoden

Equals(Object)

Gibt einen Wert zurück, der angibt, ob diese Instanz gleich einem angegebenen Objekt ist.

(Geerbt von Attribute)
GetHashCode()

Gibt den Hashcode für diese Instanz zurück.

(Geerbt von Attribute)
GetType()

Ruft den Type der aktuellen Instanz ab.

(Geerbt von Object)
IsDefaultAttribute()

Gibt beim Überschreiben in einer abgeleiteten Klasse an, ob der Wert der Instanz der Standardwert für die abgeleitete Klasse ist.

(Geerbt von Attribute)
Match(Object)

Beim Überschreiben in einer abgeleiteten Klasse wird ein Wert zurückgegeben, der angibt, ob diese Instanz einem bestimmten Objekt entspricht.

(Geerbt von Attribute)
MemberwiseClone()

Erstellt eine flache Kopie des aktuellen Object.

(Geerbt von Object)
ToString()

Gibt eine Zeichenfolge zurück, die das aktuelle Objekt darstellt.

(Geerbt von Object)

Explizite Schnittstellenimplementierungen

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

Ordnet eine Reihe von Namen einer entsprechenden Reihe von Dispatchbezeichnern zu.

(Geerbt von Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Ruft die Typinformationen für ein Objekt ab, mit deren Hilfe die Typinformationen für eine Schnittstelle abgerufen werden können.

(Geerbt von Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Ruft die Anzahl der Schnittstellen mit Typinformationen ab, die von einem Objekt bereitgestellt werden (0 oder 1).

(Geerbt von Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Stellt den Zugriff auf von einem Objekt verfügbar gemachte Eigenschaften und Methoden bereit.

(Geerbt von Attribute)

Gilt für:

Weitere Informationen