ConfigurationElementCollection Klass
Definition
Viktigt
En del information gäller för förhandsversionen av en produkt och kan komma att ändras avsevärt innan produkten blir allmänt tillgänglig. Microsoft lämnar inga garantier, uttryckliga eller underförstådda, avseende informationen som visas här.
Representerar ett konfigurationselement som innehåller en samling underordnade element.
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
- Arv
- Härledda
- Implementeringar
Exempel
I följande exempel visas hur du ConfigurationElementCollectionanvänder .
Det första exemplet består av tre klasser: UrlsSection, UrlsCollection och UrlConfigElement. Klassen UrlsSection använder för ConfigurationCollectionAttribute att definiera ett anpassat konfigurationsavsnitt. Det här avsnittet innehåller en URL-samling (definierad av UrlsCollection klassen) av URL-element (definieras av UrlConfigElement klassen).
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
I det andra kodexemplet används de klasser som angetts tidigare. Du kombinerar dessa två exempel i ett konsolprogramprojekt.
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
När du kör konsolprogrammet skapas en instans av UrlsSection klassen och följande konfigurationselement genereras i programkonfigurationsfilen:
<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
Kommentarer
ConfigurationElementCollection Representerar en samling element i en konfigurationsfil.
Note
Ett element i en konfigurationsfil refererar till ett grundläggande XML-element eller ett avsnitt. Ett enkelt element är en XML-tagg med eventuella relaterade attribut. Ett enkelt element utgör ett avsnitt. Komplexa avsnitt kan innehålla ett eller flera enkla element, en samling element och andra avsnitt.
Du använder ConfigurationElementCollection för att arbeta med en samling ConfigurationElement objekt. Implementera den här klassen för att lägga till samlingar med anpassade ConfigurationElement element i en ConfigurationSection.
Anteckningar till implementerare
Du kan använda en programmerings- eller deklarativ kodningsmodell (tillskriven) för att skapa ett anpassat konfigurationselement.
Den programmatiska modellen kräver att du för varje elementattribut skapar en egenskap för att hämta och ange dess värde och att du lägger till den i den interna egenskapsuppsättningen för den underliggande ConfigurationElement basklassen.
Med den deklarativa modellen, även kallad den tillskrivna modellen, kan du definiera ett elementattribut med hjälp av en egenskap och konfigurera den med attribut. Dessa attribut instruerar ASP.NET konfigurationssystemet om egenskapstyperna och deras standardvärden. ASP.NET kan använda reflektion för att hämta den här informationen och sedan skapa elementegenskapsobjekten och utföra den nödvändiga initieringen.
Konstruktorer
| Name | Description |
|---|---|
| ConfigurationElementCollection() |
Initierar en ny instans av ConfigurationElementCollection klassen. |
| ConfigurationElementCollection(IComparer) |
Skapar en ny instans av ConfigurationElementCollection klassen. |
Egenskaper
| Name | Description |
|---|---|
| AddElementName |
Hämtar eller anger namnet på den ConfigurationElement som ska associeras med lägg till-åtgärden i när den ConfigurationElementCollection åsidosättas i en härledd klass. |
| ClearElementName |
Hämtar eller anger namnet på den ConfigurationElement som ska associeras med clear-åtgärden i när den ConfigurationElementCollection åsidosättas i en härledd klass. |
| CollectionType |
Hämtar typen av ConfigurationElementCollection. |
| Count |
Hämtar antalet element i samlingen. |
| CurrentConfiguration |
Hämtar en referens till den översta instansen Configuration som representerar konfigurationshierarkin som den aktuella ConfigurationElement instansen tillhör. (Ärvd från ConfigurationElement) |
| ElementInformation |
Hämtar ett ElementInformation objekt som innehåller den icke-anpassningsbara informationen och funktionerna i ConfigurationElement objektet. (Ärvd från ConfigurationElement) |
| ElementName |
Hämtar namnet som används för att identifiera den här samlingen med element i konfigurationsfilen när den åsidosättas i en härledd klass. |
| ElementProperty |
Hämtar objektet ConfigurationElementProperty som representerar ConfigurationElement själva objektet. (Ärvd från ConfigurationElement) |
| EmitClear |
Hämtar eller anger ett värde som anger om samlingen har rensats. |
| EvaluationContext |
Hämtar ContextInformation-objektet för ConfigurationElement-objektet. (Ärvd från ConfigurationElement) |
| HasContext |
Hämtar ett värde som anger om egenskapen CurrentConfiguration är |
| IsSynchronized |
Hämtar ett värde som anger om åtkomsten till samlingen synkroniseras. |
| Item[ConfigurationProperty] |
Hämtar eller anger en egenskap eller ett attribut för det här konfigurationselementet. (Ärvd från ConfigurationElement) |
| Item[String] |
Hämtar eller anger en egenskap, ett attribut eller ett underordnat element i det här konfigurationselementet. (Ärvd från ConfigurationElement) |
| LockAllAttributesExcept |
Hämtar samlingen med låsta attribut. (Ärvd från ConfigurationElement) |
| LockAllElementsExcept |
Hämtar samlingen med låsta element. (Ärvd från ConfigurationElement) |
| LockAttributes |
Hämtar samlingen med låsta attribut. (Ärvd från ConfigurationElement) |
| LockElements |
Hämtar samlingen med låsta element. (Ärvd från ConfigurationElement) |
| LockItem |
Hämtar eller anger ett värde som anger om elementet är låst. (Ärvd från ConfigurationElement) |
| Properties |
Hämtar samlingen med egenskaper. (Ärvd från ConfigurationElement) |
| RemoveElementName |
Hämtar eller anger namnet på den ConfigurationElement som ska associeras med borttagningsåtgärden i när den ConfigurationElementCollection åsidosättas i en härledd klass. |
| SyncRoot |
Hämtar ett objekt som används för att synkronisera åtkomsten ConfigurationElementCollectiontill . |
| ThrowOnDuplicate |
Hämtar ett värde som anger om ett försök att lägga till en dubblett ConfigurationElement till ConfigurationElementCollection kommer att orsaka ett undantagsfel. |
Metoder
| Name | Description |
|---|---|
| BaseAdd(ConfigurationElement, Boolean) |
Lägger till ett konfigurationselement i konfigurationselementsamlingen. |
| BaseAdd(ConfigurationElement) |
Lägger till ett konfigurationselement i ConfigurationElementCollection. |
| BaseAdd(Int32, ConfigurationElement) |
Lägger till ett konfigurationselement i konfigurationselementsamlingen. |
| BaseClear() |
Tar bort alla konfigurationselementobjekt från samlingen. |
| BaseGet(Int32) |
Hämtar konfigurationselementet på den angivna indexplatsen. |
| BaseGet(Object) |
Returnerar konfigurationselementet med den angivna nyckeln. |
| BaseGetAllKeys() |
Returnerar en matris med nycklarna för alla konfigurationselement som finns i ConfigurationElementCollection. |
| BaseGetKey(Int32) |
Hämtar nyckeln för ConfigurationElement på den angivna indexplatsen. |
| BaseIndexOf(ConfigurationElement) |
Anger indexet för den angivna ConfigurationElement. |
| BaseIsRemoved(Object) |
Anger om ConfigurationElement med den angivna nyckeln har tagits bort från ConfigurationElementCollection. |
| BaseRemove(Object) |
Tar bort en ConfigurationElement från samlingen. |
| BaseRemoveAt(Int32) |
Tar ConfigurationElement bort på den angivna indexplatsen. |
| CopyTo(ConfigurationElement[], Int32) |
Kopierar innehållet i ConfigurationElementCollection till en matris. |
| CreateNewElement() |
När du åsidosättas i en härledd klass skapar du en ny ConfigurationElement. |
| CreateNewElement(String) |
Skapar en ny ConfigurationElement när den åsidosättas i en härledd klass. |
| DeserializeElement(XmlReader, Boolean) |
Läser XML från konfigurationsfilen. (Ärvd från ConfigurationElement) |
| Equals(Object) |
ConfigurationElementCollection Jämför med det angivna objektet. |
| GetElementKey(ConfigurationElement) |
Hämtar elementnyckeln för ett angivet konfigurationselement när det åsidosättas i en härledd klass. |
| GetEnumerator() |
Hämtar en IEnumerator som används för att iterera via ConfigurationElementCollection. |
| GetHashCode() |
Hämtar ett unikt värde som representerar instansen ConfigurationElementCollection . |
| GetTransformedAssemblyString(String) |
Returnerar den transformerade versionen av det angivna sammansättningsnamnet. (Ärvd från ConfigurationElement) |
| GetTransformedTypeString(String) |
Returnerar den transformerade versionen av det angivna typnamnet. (Ärvd från ConfigurationElement) |
| GetType() |
Hämtar den aktuella instansen Type . (Ärvd från Object) |
| Init() |
Anger objektets ConfigurationElement ursprungliga tillstånd. (Ärvd från ConfigurationElement) |
| InitializeDefault() |
Används för att initiera en standarduppsättning med värden för ConfigurationElement objektet. (Ärvd från ConfigurationElement) |
| IsElementName(String) |
Anger om den angivna ConfigurationElement finns i ConfigurationElementCollection. |
| IsElementRemovable(ConfigurationElement) |
Anger om den angivna ConfigurationElement kan tas bort från ConfigurationElementCollection. |
| IsModified() |
Anger om detta ConfigurationElementCollection har ändrats sedan det senast sparades eller lästes in när det åsidosattes i en härledd klass. |
| IsReadOnly() |
Anger om objektet ConfigurationElementCollection är skrivskyddat. |
| ListErrors(IList) |
Lägger till felen invalid-property i det här ConfigurationElement objektet, och i alla underelement, i den överförda listan. (Ärvd från ConfigurationElement) |
| MemberwiseClone() |
Skapar en ytlig kopia av den aktuella Object. (Ärvd från Object) |
| OnDeserializeUnrecognizedAttribute(String, String) |
Hämtar ett värde som anger om ett okänt attribut påträffas under deserialiseringen. (Ärvd från ConfigurationElement) |
| OnDeserializeUnrecognizedElement(String, XmlReader) |
Gör att konfigurationssystemet utlöser ett undantag. |
| OnRequiredPropertyNotFound(String) |
Utlöser ett undantag när en obligatorisk egenskap inte hittas. (Ärvd från ConfigurationElement) |
| PostDeserialize() |
Anropas efter deserialisering. (Ärvd från ConfigurationElement) |
| PreSerialize(XmlWriter) |
Anropas före serialisering. (Ärvd från ConfigurationElement) |
| Reset(ConfigurationElement) |
Återställer ConfigurationElementCollection till dess oförändrade tillstånd när det åsidosättas i en härledd klass. |
| ResetModified() |
Återställer värdet för egenskapen till |
| SerializeElement(XmlWriter, Boolean) |
Skriver konfigurationsdata till ett XML-element i konfigurationsfilen när de åsidosättas i en härledd klass. |
| SerializeToXmlElement(XmlWriter, String) |
Skriver de yttre taggarna för det här konfigurationselementet till konfigurationsfilen när det implementeras i en härledd klass. (Ärvd från ConfigurationElement) |
| SetPropertyValue(ConfigurationProperty, Object, Boolean) |
Anger en egenskap till det angivna värdet. (Ärvd från ConfigurationElement) |
| SetReadOnly() |
IsReadOnly() Anger egenskapen för ConfigurationElementCollection objektet och för alla underelement. |
| ToString() |
Returnerar en sträng som representerar det aktuella objektet. (Ärvd från Object) |
| Unmerge(ConfigurationElement, ConfigurationElement, ConfigurationSaveMode) |
Ändrar effekten av sammanslagning av konfigurationsinformation från olika nivåer i konfigurationshierarkin. |
Explicita gränssnittsimplementeringar
| Name | Description |
|---|---|
| ICollection.CopyTo(Array, Int32) |
Kopierar ConfigurationElementCollection till en matris. |
Tilläggsmetoder
| Name | Description |
|---|---|
| AsParallel(IEnumerable) |
Möjliggör parallellisering av en fråga. |
| AsQueryable(IEnumerable) |
Konverterar en IEnumerable till en IQueryable. |
| Cast<TResult>(IEnumerable) |
Omvandlar elementen i en IEnumerable till den angivna typen. |
| OfType<TResult>(IEnumerable) |
Filtrerar elementen i en IEnumerable baserat på en angiven typ. |