System.Configuration.ConfigurationElement 类

方法描述

表示配置文件中的配置元素。

语法定义(C# System.Configuration.ConfigurationElement 类 的用法)

public abstract class ConfigurationElement

构造函数

构造函数名称 构造函数描述
ConfigurationElement 初始化 ConfigurationElement 类的新实例。

成员/方法

方法名称 方法描述
DeserializeElement 读取配置文件中的 XML。
Equals 将当前的 ConfigurationElement 实例与指定的对象进行比较。 (重写 Object.Equals(Object)。)
Finalize 允许对象在“垃圾回收”回收之前尝试释放资源并执行其他清理操作。 (继承自 Object。)
GetHashCode 获取一个唯一值,表示当前 ConfigurationElement 实例。 (重写 Object.GetHashCode()。)
GetTransformedAssemblyString 返回指定程序集名称的转换版本。
GetTransformedTypeString 返回指定类型名称的转换版本。
GetType 获取当前实例的 Type。 (继承自 Object。)
Init 将 ConfigurationElement 对象设置为其初始状态。
InitializeDefault 用于初始化 ConfigurationElement 对象的默认值集。
IsModified 指示此配置元素自上次被保存或加载后,直到在派生类中被实现时,是否已经更改。
IsReadOnly 获取一个值,该值指示 ConfigurationElement 对象是否为只读。
ListErrors 将此 ConfigurationElement 对象以及所有子元素中无效属性的错误添加到传递的列表中。
MemberwiseClone 创建当前 Object 的浅表副本。 (继承自 Object。)
OnDeserializeUnrecognizedAttribute 获取一个值,该值指示反序列化过程中是否遇到未知特性。
OnDeserializeUnrecognizedElement 获取一个值,该值指示反序列化过程中是否遇到未知元素。
OnRequiredPropertyNotFound 未找到所需属性时引发异常。
PostDeserialize 反序列化后调用。
PreSerialize 序列化前调用。
Reset 重置 ConfigurationElement 对象的内部状态,包括锁和属性集合。
ResetModified 在派生类中实现时,将 IsModified 方法的值重置为 false。
SerializeElement 当在派生类中实现后,将此配置元素的内容写入配置文件。
SerializeToXmlElement 当在派生类中实现后,将此配置元素的外部标记写入配置文件。
SetPropertyValue 将属性设置为指定值。
SetReadOnly 设置 ConfigurationElement 对象及所有子元素的 IsReadOnly 属性。
ToString 返回表示当前对象的字符串。 (继承自 Object。)
Unmerge 修改 ConfigurationElement 对象以移除所有将不被保存的值。

提示和注释

ConfigurationElement 是一个用于表示配置文件(如 Web.config)中 XML 元素的抽象类。 配置文件中的元素可以包含零个、一个或多个子元素。

因为 ConfigurationElement 类定义为抽象类,所以无法创建它的实例。 只能从它派生类。 .NET Framework 包括从 ConfigurationElement 类派生出的类,为了能够表示标准的 XML 配置元素,如 ConfigurationSection。 也可以扩展 ConfigurationElement 类,以访问自定义配置元素和节。 在本主题后面的示例演示如何通过使用从 ConfigurationElement 派生的自定义类来访问自定义配置元素和部分。

还可以扩展标准配置类型,例如 ConfigurationElement、ConfigurationElementCollection、ConfigurationProperty 和 ConfigurationSection。 有关更多信息,请参见那些类的文档。

有关如何访问配置文件中信息的更多信息,请参见 ConfigurationManager 类和 WebConfigurationManager 类。

对继承者的说明

每个 ConfigurationElement 对象都为表示其元素特性或子元素集合的 ConfigurationProperty 对象创建一个内部的 ConfigurationPropertyCollection 集合。

无法自定义的信息和功能都包含在 ElementInformation 属性所提供的 ElementInformation 对象中。

可以使用编程或声明性(特性化)代码编写模型创建自定义配置元素:

编程模型要求为每个元素特性创建一个用于获取或设置其值的属性,并将其添加到基础 ConfigurationElement 基类的内部属性包中。 请参见 ConfigurationSection 类,以获得有关如何使用此模型的示例。

此声明性模型(也称为特性化模型)相对简单,它允许您使用属性定义一个元素特性,然后再用特性对该元素特性进行修饰。 这些特性将属性类型及其默认值通知给 ASP.NET 配置系统。 利用通过反射获取的此信息,ASP.NET 配置系统将创建元素属性对象,并执行所需的初始化。 本主题稍后显示的示例介绍如何使用此模型。

System.Configuration.ConfigurationElement 类例子

None 复制

VB 复制 ' Set Assembly name to ConfigurationElement ' and set Root namespace to Samples.AspNet Imports System Imports System.Configuration Imports System.Collections Class TestConfigurationElement ' Entry point for console application that reads the ' app.config file and writes to the console the ' URLs in the custom section. Shared Sub Main(ByVal args() As String) ' Get the current configuration file. Dim config As System.Configuration.Configuration = _ ConfigurationManager.OpenExeConfiguration( _ ConfigurationUserLevel.None) ' Get the MyUrls section. Dim myUrlsSection As UrlsSection = _ config.GetSection("MyUrls") If myUrlsSection Is Nothing Then Console.WriteLine("Failed to load UrlsSection.") Else Console.WriteLine("The 'simple' element of app.config:") Console.WriteLine(" Name={0} URL={1} Port={2}", _ myUrlsSection.Simple.Name, _ myUrlsSection.Simple.Url, _ myUrlsSection.Simple.Port) Console.WriteLine("The urls collection of app.config:") Dim i As Integer For i = 0 To myUrlsSection.Urls.Count - 1 Console.WriteLine(" Name={0} URL={1} Port={2}", _ i, myUrlsSection.Urls(i).Name, _ myUrlsSection.Urls(i).Url, _ myUrlsSection.Urls(i).Port) Next i End If Console.ReadLine() End Sub End Class C# 复制 // Set Assembly name to ConfigurationElement using System; using System.Configuration; using System.Collections; namespace Samples.AspNet { // Entry point for console application that reads the // app.config file and writes to the console the // URLs in the custom section. class TestConfigurationElement { static void Main(string[] args) { // Get current configuration file. System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration( ConfigurationUserLevel.None); // Get the MyUrls section. UrlsSection myUrlsSection = config.GetSection("MyUrls") as UrlsSection; if (myUrlsSection == null) Console.WriteLine("Failed to load UrlsSection."); else { Console.WriteLine("The 'simple' element of app.config:"); Console.WriteLine(" Name={0} URL={1} Port={2}", myUrlsSection.Simple.Name, myUrlsSection.Simple.Url, myUrlsSection.Simple.Port); Console.WriteLine("The urls collection of app.config:"); 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); } } Console.ReadLine(); } } } VB 复制 Imports System Imports System.Configuration Imports System.Collections ' Define a custom section containing an individual ' element and a collection of elements. Public Class UrlsSection Inherits ConfigurationSection _ Public Property Name() As String Get Return CStr(Me("name")) End Get Set(ByVal value As String) Me("name") = value End Set End Property ' Declare an element (not in a collection) of the type ' UrlConfigElement. In the configuration ' file it corresponds to . _ Public ReadOnly Property Simple() _ As UrlConfigElement Get Dim url As UrlConfigElement = _ CType(Me("simple"), _ UrlConfigElement) Return url End Get End Property ' Declare a collection element represented ' in the configuration file by the sub-section ' ' Note: the "IsDefaultCollection = false" ' instructs the .NET Framework to build a nested ' section like .... _ Public ReadOnly Property Urls() _ As UrlsCollection Get Dim urlsCollection _ As UrlsCollection = _ CType(Me("urls"), UrlsCollection) Return urlsCollection End Get End Property Protected Overrides Sub DeserializeSection( _ ByVal reader As System.Xml.XmlReader) MyBase.DeserializeSection(reader) ' Enter your custom processing code here. End Sub 'DeserializeSection Protected Overrides Function SerializeSection( _ ByVal parentElement As ConfigurationElement, _ ByVal name As String, _ ByVal saveMode As ConfigurationSaveMode) As String Dim s As String = _ MyBase.SerializeSection(parentElement, _ name, saveMode) ' Enter your custom processing code here. Return s End Function 'SerializeSection End Class 'UrlsSection C# 复制 using System; using System.Configuration; using System.Collections; namespace Samples.AspNet { // Define a custom section containing an individual // element and a collection of elements. public class UrlsSection : ConfigurationSection { [ConfigurationProperty("name", DefaultValue = "MyFavorites", IsRequired = true, IsKey = false)] [StringValidator(InvalidCharacters = " ~!@#$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 60)] public string Name { get { return (string)this["name"]; } set { this["name"] = value; } } // Declare an element (not in a collection) of the type // UrlConfigElement. In the configuration // file it corresponds to . [ConfigurationProperty("simple")] public UrlConfigElement Simple { get { UrlConfigElement url = (UrlConfigElement)base["simple"]; return url; } } // Declare a collection element represented // in the configuration file by the sub-section // // Note: the "IsDefaultCollection = false" // instructs the .NET Framework to build a nested // section like .... [ConfigurationProperty("urls", IsDefaultCollection = false)] public UrlsCollection Urls { get { UrlsCollection urlsCollection = (UrlsCollection)base["urls"]; return urlsCollection; } } protected override void DeserializeSection( System.Xml.XmlReader reader) { base.DeserializeSection(reader); // You can add custom processing code here. } protected override string SerializeSection( ConfigurationElement parentElement, string name, ConfigurationSaveMode saveMode) { string s = base.SerializeSection(parentElement, name, saveMode); // You can add custom processing code here. return s; } } } VB 复制 Imports System Imports System.Configuration Imports System.Collections Public Class UrlsCollection Inherits ConfigurationElementCollection Public Sub New() ' Add one url to the collection. This is ' not necessary; could leave the collection ' empty until items are added to it outside ' the constructor. Dim url As UrlConfigElement = _ CType(CreateNewElement(), UrlConfigElement) ' Add the element to the collection. Add(url) End Sub 'New 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 'CreateNewElement Protected Overloads Overrides Function CreateNewElement( _ ByVal elementName As String) _ As ConfigurationElement Return New UrlConfigElement(elementName) End Function 'CreateNewElement Protected Overrides Function GetElementKey( _ ByVal element As ConfigurationElement) As [Object] Return CType(element, UrlConfigElement).Name End Function 'GetElementKey Public Shadows Property AddElementName() As String Get Return MyBase.AddElementName End Get Set(ByVal value As String) MyBase.AddElementName = value End Set End Property Public Shadows Property ClearElementName() As String Get Return MyBase.ClearElementName End Get Set(ByVal value As String) MyBase.AddElementName = value End Set End Property Public Shadows ReadOnly Property RemoveElementName() As String Get Return MyBase.RemoveElementName End Get End Property Public Shadows ReadOnly Property Count() As Integer Get Return MyBase.Count End Get End Property 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 Not (BaseGet(index) Is 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 'IndexOf Public Sub Add(ByVal url As UrlConfigElement) BaseAdd(url) ' Add custom code here. End Sub 'Add Protected Overrides Sub BaseAdd( _ ByVal element As ConfigurationElement) BaseAdd(element, False) ' Add custom code here. End Sub 'BaseAdd Public Overloads Sub Remove( _ ByVal url As UrlConfigElement) If BaseIndexOf(url) >= 0 Then BaseRemove(url.Name) End If End Sub 'Remove Public Sub RemoveAt(ByVal index As Integer) BaseRemoveAt(index) End Sub 'RemoveAt Public Overloads Sub Remove(ByVal name As String) BaseRemove(name) End Sub 'Remove Public Sub Clear() BaseClear() End Sub 'Clear ' End Class 'UrlsCollection C# 复制 using System; using System.Configuration; using System.Collections; namespace Samples.AspNet { public class UrlsCollection : ConfigurationElementCollection { public UrlsCollection() { // Add one url to the collection. This is // not necessary; could leave the collection // empty until items are added to it outside // the constructor. UrlConfigElement url = (UrlConfigElement)CreateNewElement(); Add(url); } public override ConfigurationElementCollectionType CollectionType { get { return ConfigurationElementCollectionType.AddRemoveClearMap; } } protected override ConfigurationElement CreateNewElement() { return new UrlConfigElement(); } protected override ConfigurationElement CreateNewElement( string elementName) { return new UrlConfigElement(elementName); } protected override Object GetElementKey(ConfigurationElement element) { return ((UrlConfigElement)element).Name; } public new string AddElementName { get { return base.AddElementName; } set { base.AddElementName = value; } } public new string ClearElementName { get { return base.ClearElementName; } set { base.AddElementName = value; } } public new string RemoveElementName { get { return base.RemoveElementName; } } public new int Count { get { return base.Count; } } 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); // Add custom code here. } protected override void BaseAdd(ConfigurationElement element) { BaseAdd(element, false); // Add custom code here. } 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(); // Add custom code here. } } } VB 复制 Imports System Imports System.Configuration Imports System.Collections Public Class UrlConfigElement Inherits ConfigurationElement ' Constructor allowing name, url, and port to be specified. Public Sub New(ByVal newName As String, _ ByVal newUrl As String, _ ByVal newPort As Integer) Name = newName Url = newUrl Port = newPort End Sub 'New ' Default constructor, will use default values as defined Public Sub New() End Sub 'New ' Constructor allowing name to be specified, will take the ' default values for url and port. Public Sub New(ByVal elementName As String) Name = elementName End Sub 'New _ Public Property Name() As String Get Return CStr(Me("name")) End Get Set(ByVal value As String) Me("name") = value End Set End Property _ Public Property Url() As String Get Return CStr(Me("url")) End Get Set(ByVal value As String) Me("url") = value End Set End Property _ Public Property Port() As Integer Get Return Fix(Me("port")) End Get Set(ByVal value As Integer) Me("port") = value End Set End Property Protected Overrides Sub DeserializeElement(ByVal reader _ As System.Xml.XmlReader, _ ByVal serializeCollectionKey As Boolean) MyBase.DeserializeElement(reader, _ serializeCollectionKey) ' Enter your custom processing code here. End Sub 'DeserializeElement Protected Overrides Function SerializeElement(ByVal writer _ As System.Xml.XmlWriter, _ ByVal serializeCollectionKey As Boolean) As Boolean Dim ret As Boolean = _ MyBase.SerializeElement(writer, serializeCollectionKey) ' Enter your custom processing code here. Return ret End Function 'SerializeElement Protected Overrides Function IsModified() As Boolean Dim ret As Boolean = MyBase.IsModified() ' Enter your custom processing code here. Return ret End Function 'IsModified End Class 'UrlConfigElement C# 复制 using System; using System.Configuration; using System.Collections; namespace Samples.AspNet { public class UrlConfigElement : ConfigurationElement { // Constructor allowing name, url, and port to be specified. public UrlConfigElement(String newName, String newUrl, int newPort) { Name = newName; Url = newUrl; Port = newPort; } // Default constructor, will use default values as defined // below. public UrlConfigElement() { } // Constructor allowing name to be specified, will take the // default values for url and port. public UrlConfigElement(string elementName) { Name = elementName; } [ConfigurationProperty("name", DefaultValue = "Microsoft", IsRequired = true, IsKey = true)] public string Name { get { return (string)this["name"]; } set { this["name"] = value; } } [ConfigurationProperty("url", DefaultValue = "http://www.microsoft.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; } } protected override void DeserializeElement( System.Xml.XmlReader reader, bool serializeCollectionKey) { base.DeserializeElement(reader, serializeCollectionKey); // You can your custom processing code here. } protected override bool SerializeElement( System.Xml.XmlWriter writer, bool serializeCollectionKey) { bool ret = base.SerializeElement(writer, serializeCollectionKey); // You can enter your custom processing code here. return ret; } protected override bool IsModified() { bool ret = base.IsModified(); // You can enter your custom processing code here. return ret; } } }

using System;
using System.Configuration;
using System.Collections;

namespace Samples.AspNet
{
    public class UrlConfigElement : ConfigurationElement
    {
        // Constructor allowing name, url, and port to be specified.
        public UrlConfigElement(String newName,
            String newUrl, int newPort)
        {
            Name = newName;
            Url = newUrl;
            Port = newPort;
        }

        // Default constructor, will use default values as defined
        // below.
        public UrlConfigElement()
        {
        }

        // Constructor allowing name to be specified, will take the
        // default values for url and port.
        public UrlConfigElement(string elementName)
        {
            Name = elementName;
        }

        [ConfigurationProperty("name", 
            DefaultValue = "Microsoft",
            IsRequired = true, 
            IsKey = true)]
        public string Name
        {
            get
            {
                return (string)this["name"];
            }
            set
            {
                this["name"] = value;
            }
        }

        [ConfigurationProperty("url",
            DefaultValue = "http://www.microsoft.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;
            }
        }

        protected override void DeserializeElement(
           System.Xml.XmlReader reader, 
            bool serializeCollectionKey)
        {
            base.DeserializeElement(reader, 
                serializeCollectionKey);
            // You can your custom processing code here.
        }


        protected override bool SerializeElement(
            System.Xml.XmlWriter writer, 
            bool serializeCollectionKey)
        {
            bool ret = base.SerializeElement(writer, 
                serializeCollectionKey);
            // You can enter your custom processing code here.
            return ret;

        }


        protected override bool IsModified()
        {
            bool ret = base.IsModified();
            // You can enter your custom processing code here.
            return ret;
        }
    }
}

继承层次结构

System.Object

System.Configuration.ConfigurationElement

更多...

命名空间

namespace: System.Configuration

程序集: System.Configuration(在 System.Configuration.dll 中)

线程安全

此类型的任何公共 static(在 Visual Basic 中为 Shared) 成员都是线程安全的。但不保证所有实例成员都是线程安全的。

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。