ConfigurationElementCollection 类
定义
表示一个配置元素,该元素包含子元素的集合。Represents a configuration element containing a collection of child elements.
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
- 继承
- 派生
- 实现
示例
下面的示例演示如何使用 ConfigurationElementCollection 。The following example shows how to use the ConfigurationElementCollection.
第一个示例包含三个类: UrlsSection
、 UrlsCollection
和 UrlConfigElement
。The first example consists of three classes: UrlsSection
, UrlsCollection
and UrlConfigElement
. UrlsSection
类使用 ConfigurationCollectionAttribute 来定义自定义配置节。The UrlsSection
class uses the ConfigurationCollectionAttribute to define a custom configuration section. 此部分包含由类 UrlsCollection
) 定义 (url 元素的类) 定义的 url 集合 (UrlConfigElement
。This section contains a URL collection (defined by the UrlsCollection
class) of URL elements (defined by the UrlConfigElement
class).
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
此第二个代码示例使用前面指定的类。This second code example uses the classes specified before. 在控制台应用程序项目中将这两个示例组合在一起。You combine these two examples in a console application project.
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
运行控制台应用程序时, UrlsSection
会创建类的一个实例,并在应用程序配置文件中生成以下配置元素:When you run the console application, an instance of the UrlsSection
class is created and the following configuration elements are generated in the application configuration file:
<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
注解
ConfigurationElementCollection表示配置文件中的元素的集合。The ConfigurationElementCollection represents a collection of elements within a configuration file.
备注
配置文件中的元素引用基本 XML 元素或节。An element within a configuration file refers to a basic XML element or a section. 简单元素是具有相关属性的 XML 标记(如果有)。A simple element is an XML tag with related attributes, if any. 简单元素构成一个部分。A simple element constitutes a section. 复杂节可以包含一个或多个简单元素、元素集合以及其他部分。Complex sections can contain one or more simple elements, a collection of elements, and other sections.
您可以使用 ConfigurationElementCollection 来处理对象的集合 ConfigurationElement 。You use the ConfigurationElementCollection to work with a collection of ConfigurationElement objects. 实现此类可将自定义元素的集合添加 ConfigurationElement 到 ConfigurationSection 。Implement this class to add collections of custom ConfigurationElement elements to a ConfigurationSection.
实施者说明
您可以使用编程方式或声明性 (特性化) 编码模型来创建自定义配置元素。You can use a programmatic or a declarative (attributed) coding model to create a custom configuration element.
编程模型要求为每个元素特性创建一个属性以获取并设置其值,并将其添加到基础基类的内部属性包 ConfigurationElement 。The programmatic model requires that for each element attribute you create a property to get and set its value, and that you add it to the internal property bag of the underlying ConfigurationElement base class.
声明性模型(也称为特性化模型)允许您通过使用属性并使用特性配置元素特性来定义元素特性。The declarative model, also referred to as the attributed model, allows you to define an element attribute by using a property and configuring it with attributes. 这些属性指示 ASP.NET 配置系统有关属性类型及其默认值的信息。These attributes instruct the ASP.NET configuration system about the property types and their default values. ASP.NET 可以使用反射来获取此信息,然后创建元素属性对象并执行所需的初始化。ASP.NET can use reflection to obtain this information and then create the element property objects and perform the required initialization.
构造函数
ConfigurationElementCollection() |
初始化 ConfigurationElementCollection 类的新实例。Initializes a new instance of the ConfigurationElementCollection class. |
ConfigurationElementCollection(IComparer) |
创建 ConfigurationElementCollection 类的新实例。Creates a new instance of the ConfigurationElementCollection class. |
属性
AddElementName |
在派生的类中重写时,获取或设置 ConfigurationElement 的名称,以便在 ConfigurationElementCollection 中与添加操作关联。Gets or sets the name of the ConfigurationElement to associate with the add operation in the ConfigurationElementCollection when overridden in a derived class. |
ClearElementName |
在派生的类中重写时,获取或设置 ConfigurationElement 的名称,以便在 ConfigurationElementCollection 中与清除操作关联。Gets or sets the name for the ConfigurationElement to associate with the clear operation in the ConfigurationElementCollection when overridden in a derived class. |
CollectionType |
获取 ConfigurationElementCollection 的类型。Gets the type of the ConfigurationElementCollection. |
Count |
获取集合中的元素数。Gets the number of elements in the collection. |
CurrentConfiguration |
获取对顶级 Configuration 实例的引用,该实例表示当前 ConfigurationElement 实例所属的配置层次结构。Gets a reference to the top-level Configuration instance that represents the configuration hierarchy that the current ConfigurationElement instance belongs to. (继承自 ConfigurationElement) |
ElementInformation |
获取包含 ConfigurationElement 对象的不可自定义的信息和功能的 ElementInformation 对象。Gets an ElementInformation object that contains the non-customizable information and functionality of the ConfigurationElement object. (继承自 ConfigurationElement) |
ElementName |
获取在派生的类中重写时用于标识配置文件中此元素集合的名称。Gets the name used to identify this collection of elements in the configuration file when overridden in a derived class. |
ElementProperty |
获取表示 ConfigurationElement 对象本身的 ConfigurationElementProperty 对象。Gets the ConfigurationElementProperty object that represents the ConfigurationElement object itself. (继承自 ConfigurationElement) |
EmitClear |
获取或设置一个值,该值指定是否已清除集合。Gets or sets a value that specifies whether the collection has been cleared. |
EvaluationContext |
获取 ConfigurationElement 对象的 ContextInformation 对象。Gets the ContextInformation object for the ConfigurationElement object. (继承自 ConfigurationElement) |
HasContext |
获取一个值,该值指示 CurrentConfiguration 属性是否为 |
IsSynchronized |
获取一个值,该值指示是否同步对集合的访问。Gets a value indicating whether access to the collection is synchronized. |
Item[ConfigurationProperty] |
获取或设置此配置元素的属性或特性。Gets or sets a property or attribute of this configuration element. (继承自 ConfigurationElement) |
Item[String] |
获取或设置此配置元素的属性、特性或子元素。Gets or sets a property, attribute, or child element of this configuration element. (继承自 ConfigurationElement) |
LockAllAttributesExcept |
获取被锁定的特性的集合。Gets the collection of locked attributes. (继承自 ConfigurationElement) |
LockAllElementsExcept |
获取被锁定的元素的集合。Gets the collection of locked elements. (继承自 ConfigurationElement) |
LockAttributes |
获取被锁定的特性的集合。Gets the collection of locked attributes. (继承自 ConfigurationElement) |
LockElements |
获取被锁定的元素的集合。Gets the collection of locked elements. (继承自 ConfigurationElement) |
LockItem |
获取或设置一个值,该值指示是否已锁定该元素。Gets or sets a value indicating whether the element is locked. (继承自 ConfigurationElement) |
Properties |
获取属性的集合。Gets the collection of properties. (继承自 ConfigurationElement) |
RemoveElementName |
在派生的类中重写时,获取或设置 ConfigurationElement 的名称,以便在 ConfigurationElementCollection 中与移除操作关联。Gets or sets the name of the ConfigurationElement to associate with the remove operation in the ConfigurationElementCollection when overridden in a derived class. |
SyncRoot |
获取用于同步对 ConfigurationElementCollection 的访问的对象。Gets an object used to synchronize access to the ConfigurationElementCollection. |
ThrowOnDuplicate |
获取一个值,该值指示尝试向 ConfigurationElement 添加重复的 ConfigurationElementCollection 是否会导致引发异常。Gets a value indicating whether an attempt to add a duplicate ConfigurationElement to the ConfigurationElementCollection will cause an exception to be thrown. |
方法
BaseAdd(ConfigurationElement) |
向 ConfigurationElementCollection 添加配置元素。Adds a configuration element to the ConfigurationElementCollection. |
BaseAdd(ConfigurationElement, Boolean) |
向配置元素集合添加配置元素。Adds a configuration element to the configuration element collection. |
BaseAdd(Int32, ConfigurationElement) |
向配置元素集合添加配置元素。Adds a configuration element to the configuration element collection. |
BaseClear() |
从集合中移除所有配置元素对象。Removes all configuration element objects from the collection. |
BaseGet(Int32) |
获取位于指定索引位置的配置元素。Gets the configuration element at the specified index location. |
BaseGet(Object) |
返回具有指定键的配置元素。Returns the configuration element with the specified key. |
BaseGetAllKeys() |
返回 ConfigurationElementCollection 中包含的所有配置元素的键数组。Returns an array of the keys for all of the configuration elements contained in the ConfigurationElementCollection. |
BaseGetKey(Int32) |
获取位于指定索引位置的 ConfigurationElement 的键。Gets the key for the ConfigurationElement at the specified index location. |
BaseIndexOf(ConfigurationElement) |
获取指定的 ConfigurationElement 的索引。Indicates the index of the specified ConfigurationElement. |
BaseIsRemoved(Object) |
指示是否已从 ConfigurationElement 中移除具有指定键的 ConfigurationElementCollection。Indicates whether the ConfigurationElement with the specified key has been removed from the ConfigurationElementCollection. |
BaseRemove(Object) |
从集合中删除 ConfigurationElement 对象。Removes a ConfigurationElement from the collection. |
BaseRemoveAt(Int32) |
移除位于指定索引位置的 ConfigurationElement。Removes the ConfigurationElement at the specified index location. |
CopyTo(ConfigurationElement[], Int32) |
将 ConfigurationElementCollection 的内容复制到数组。Copies the contents of the ConfigurationElementCollection to an array. |
CreateNewElement() |
在派生的类中重写时,创建一个新的 ConfigurationElement。When overridden in a derived class, creates a new ConfigurationElement. |
CreateNewElement(String) |
在派生的类中重写时,创建新的 ConfigurationElement。Creates a new ConfigurationElement when overridden in a derived class. |
DeserializeElement(XmlReader, Boolean) |
从配置文件读取 XML。Reads XML from the configuration file. (继承自 ConfigurationElement) |
Equals(Object) |
将 ConfigurationElementCollection 与指定的对象进行比较。Compares the ConfigurationElementCollection to the specified object. |
GetElementKey(ConfigurationElement) |
在派生类中重写时获取指定配置元素的元素键。Gets the element key for a specified configuration element when overridden in a derived class. |
GetEnumerator() |
获取用于循环访问 IEnumerator 的 ConfigurationElementCollection。Gets an IEnumerator which is used to iterate through the ConfigurationElementCollection. |
GetHashCode() |
获取表示 ConfigurationElementCollection 实例的唯一值。Gets a unique value representing the ConfigurationElementCollection instance. |
GetTransformedAssemblyString(String) |
返回指定程序集名称的转换版本。Returns the transformed version of the specified assembly name. (继承自 ConfigurationElement) |
GetTransformedTypeString(String) |
返回指定类型名称的转换版本。Returns the transformed version of the specified type name. (继承自 ConfigurationElement) |
GetType() |
获取当前实例的 Type。Gets the Type of the current instance. (继承自 Object) |
Init() |
将 ConfigurationElement 对象设置为其初始状态。Sets the ConfigurationElement object to its initial state. (继承自 ConfigurationElement) |
InitializeDefault() |
用于初始化 ConfigurationElement 对象的默认值集。Used to initialize a default set of values for the ConfigurationElement object. (继承自 ConfigurationElement) |
IsElementName(String) |
指示指定的 ConfigurationElement 是否存在于 ConfigurationElementCollection 中。Indicates whether the specified ConfigurationElement exists in the ConfigurationElementCollection. |
IsElementRemovable(ConfigurationElement) |
指示是否可从 ConfigurationElement 中移除指定 ConfigurationElementCollection。Indicates whether the specified ConfigurationElement can be removed from the ConfigurationElementCollection. |
IsModified() |
在派生的类中重写时,指示从最后一次保存或加载此 ConfigurationElementCollection 后是否对其进行了修改。Indicates whether this ConfigurationElementCollection has been modified since it was last saved or loaded when overridden in a derived class. |
IsReadOnly() |
指示 ConfigurationElementCollection 对象是否为只读的。Indicates whether the ConfigurationElementCollection object is read only. |
ListErrors(IList) |
将此 ConfigurationElement 对象以及所有子元素中无效属性的错误添加到传递的列表中。Adds the invalid-property errors in this ConfigurationElement object, and in all subelements, to the passed list. (继承自 ConfigurationElement) |
MemberwiseClone() |
创建当前 Object 的浅表副本。Creates a shallow copy of the current Object. (继承自 Object) |
OnDeserializeUnrecognizedAttribute(String, String) |
获取一个值,该值指示反序列化过程中是否遇到未知特性。Gets a value indicating whether an unknown attribute is encountered during deserialization. (继承自 ConfigurationElement) |
OnDeserializeUnrecognizedElement(String, XmlReader) |
导致配置系统引发异常。Causes the configuration system to throw an exception. |
OnRequiredPropertyNotFound(String) |
找不到所需属性时引发异常。Throws an exception when a required property is not found. (继承自 ConfigurationElement) |
PostDeserialize() |
反序列化后调用。Called after deserialization. (继承自 ConfigurationElement) |
PreSerialize(XmlWriter) |
在序列化之前调用。Called before serialization. (继承自 ConfigurationElement) |
Reset(ConfigurationElement) |
在派生的类中重写时,将 ConfigurationElementCollection 重置为其未被修改时的状态。Resets the ConfigurationElementCollection to its unmodified state when overridden in a derived class. |
ResetModified() |
在派生的类中重写时,将 IsModified() 属性的值重置为 |
SerializeElement(XmlWriter, Boolean) |
在派生的类中重写时,将配置数据写入配置文件中的 XML 元素。Writes the configuration data to an XML element in the configuration file when overridden in a derived class. |
SerializeToXmlElement(XmlWriter, String) |
当在派生类中实现后,将此配置元素的外部标记写入配置文件。Writes the outer tags of this configuration element to the configuration file when implemented in a derived class. (继承自 ConfigurationElement) |
SetPropertyValue(ConfigurationProperty, Object, Boolean) |
将属性设置为指定值。Sets a property to the specified value. (继承自 ConfigurationElement) |
SetReadOnly() |
为 IsReadOnly() 对象和所有子元素设置 ConfigurationElementCollection 属性。Sets the IsReadOnly() property for the ConfigurationElementCollection object and for all sub-elements. |
ToString() |
返回表示当前对象的字符串。Returns a string that represents the current object. (继承自 Object) |
Unmerge(ConfigurationElement, ConfigurationElement, ConfigurationSaveMode) |
反转从配置层次结构的不同级别合并配置信息的效果。Reverses the effect of merging configuration information from different levels of the configuration hierarchy. |
显式接口实现
ICollection.CopyTo(Array, Int32) |
将 ConfigurationElementCollection 复制到数组。Copies the ConfigurationElementCollection to an array. |
扩展方法
Cast<TResult>(IEnumerable) |
将 IEnumerable 的元素强制转换为指定的类型。Casts the elements of an IEnumerable to the specified type. |
OfType<TResult>(IEnumerable) |
根据指定类型筛选 IEnumerable 的元素。Filters the elements of an IEnumerable based on a specified type. |
AsParallel(IEnumerable) |
启用查询的并行化。Enables parallelization of a query. |
AsQueryable(IEnumerable) |
将 IEnumerable 转换为 IQueryable。Converts an IEnumerable to an IQueryable. |