System.Configuration.ConfigurationCollectionAttribute 类

方法描述

以声明的方式指示 .NET Framework 创建配置元素集合的实例。 此类不能被继承。

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

[AttributeUsageAttribute(AttributeTargets.Class|AttributeTargets.Property)]
public sealed class ConfigurationCollectionAttribute : Attribute

构造函数

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

成员/方法

方法名称 方法描述
Equals 基础结构。返回一个值,该值指示此实例是否与指定的对象相等。 (继承自 Attribute。)
Finalize 允许对象在“垃圾回收”回收之前尝试释放资源并执行其他清理操作。 (继承自 Object。)
GetHashCode 返回此实例的哈希代码。 (继承自 Attribute。)
GetType 获取当前实例的 Type。 (继承自 Object。)
IsDefaultAttribute 当在派生类中重写时,指示此实例的值是否是派生类的默认值。 (继承自 Attribute。)
Match 当在派生类中重写时,返回一个指示此实例是否等于指定对象的值。 (继承自 Attribute。)
MemberwiseClone 创建当前 Object 的浅表副本。 (继承自 Object。)
ToString 返回表示当前对象的字符串。 (继承自 Object。)

提示和注释

使用 ConfigurationCollectionAttribute 特性修饰 ConfigurationElementCollection 元素。 这将指示 .NET Framework 创建集合的实例并使用自定义 ConfigurationElement 值初始化该集合。

注意

创建自定义配置元素最简便的方法就是使用特性化(声明性)模型。 声明这些元素并用 ConfigurationCollectionAttribute 特性修饰它们。 对于每个用此特性标记的元素,.NET Framework 使用反射读取修饰参数并创建相关的 ConfigurationElementCollection 实例。 您也可以使用编程模型。 在这种情况下,您负责声明自定义公共集合,同时还要重写 ConfigurationElementCollection 成员并返回属性集合。

.NET Framework 配置系统提供的特性类型可在创建自定义配置元素期间使用。 有两种特性:

指示 .NET Framework 如何创建自定义配置元素属性实例的特性。 这些类型包括:

ConfigurationCollectionAttribute

ConfigurationPropertyAttribute

指示 .NET Framework 如何验证自定义配置元素属性的特性。 这些类型包括:

IntegerValidatorAttribute

LongValidatorAttribute

RegexStringValidatorAttribute

StringValidatorAttribute

TimeSpanValidatorAttribute

System.Configuration.ConfigurationCollectionAttribute 类例子

VB 复制 Imports System Imports System.Configuration ' Define a custom section that contains a custom ' UrlsCollection collection of custom UrlConfigElement elements. ' This class shows how to use the ConfigurationCollectionAttribute. Public Class UrlsSection Inherits ConfigurationSection ' Declare the Urls collection property using the ' ConfigurationCollectionAttribute. ' This allows to build a nested section that contains ' a collection of elements. _ Public ReadOnly Property Urls() As UrlsCollection Get Dim urlsCollection As UrlsCollection = CType(MyBase.Item("urls"), UrlsCollection) Return urlsCollection End Get End Property End Class ' Define the custom UrlsCollection that contains the ' custom UrlsConfigElement elements. Public Class UrlsCollection Inherits ConfigurationElementCollection Public Sub New() Dim url As UrlConfigElement = CType(CreateNewElement(), UrlConfigElement) Add(url) End Sub Public Overrides ReadOnly Property CollectionType() As ConfigurationElementCollectionType Get Return ConfigurationElementCollectionType.AddRemoveClearMap End Get End Property Protected Overloads Overrides Function CreateNewElement() As ConfigurationElement Return New UrlConfigElement() End Function Protected Overrides Function GetElementKey(ByVal element As ConfigurationElement) As Object Return (CType(element, UrlConfigElement)).Name End Function Default Shadows Property Item(ByVal index As Integer) As UrlConfigElement Get Return CType(BaseGet(index), UrlConfigElement) End Get Set(ByVal value As UrlConfigElement) If BaseGet(index) IsNot Nothing Then BaseRemoveAt(index) End If BaseAdd(index, value) End Set End Property Default Public Shadows ReadOnly Property Item(ByVal Name As String) As UrlConfigElement Get Return CType(BaseGet(Name), UrlConfigElement) End Get End Property Public Function IndexOf(ByVal url As UrlConfigElement) As Integer Return BaseIndexOf(url) End Function Public Sub Add(ByVal url As UrlConfigElement) BaseAdd(url) End Sub Protected Overloads Overrides Sub BaseAdd(ByVal element As ConfigurationElement) BaseAdd(element, False) End Sub Public Sub Remove(ByVal url As UrlConfigElement) If BaseIndexOf(url) >= 0 Then BaseRemove(url.Name) End If End Sub Public Sub RemoveAt(ByVal index As Integer) BaseRemoveAt(index) End Sub Public Sub Remove(ByVal name As String) BaseRemove(name) End Sub Public Sub Clear() BaseClear() End Sub End Class ' Define the custom UrlsConfigElement elements that are contained ' by the custom UrlsCollection. Public Class UrlConfigElement Inherits ConfigurationElement Public Sub New(ByVal name As String, ByVal url As String) Me.Name = name Me.Url = url End Sub Public Sub New() Me.Name = "Contoso" Me.Url = "http://www.contoso.com" Me.Port = 0 End Sub _ 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 CInt(Fix(Me("port"))) End Get Set(ByVal value As Integer) Me("port") = value End Set End Property End Class C# 复制 using System; using System.Configuration; // Define a custom section that contains a custom // UrlsCollection collection of custom UrlConfigElement elements. // This class shows how to use the ConfigurationCollectionAttribute. public class UrlsSection : ConfigurationSection { // Declare the Urls collection property using the // ConfigurationCollectionAttribute. // This allows to build a nested section that contains // a collection of elements. [ConfigurationProperty("urls", IsDefaultCollection = false)] [ConfigurationCollection(typeof(UrlsCollection), AddItemName = "add", ClearItemsName = "clear", RemoveItemName = "remove")] public UrlsCollection Urls { get { UrlsCollection urlsCollection = (UrlsCollection)base["urls"]; return urlsCollection; } } } // Define the custom UrlsCollection that contains the // custom UrlsConfigElement elements. public class UrlsCollection : ConfigurationElementCollection { public UrlsCollection() { UrlConfigElement url = (UrlConfigElement)CreateNewElement(); Add(url); } public override ConfigurationElementCollectionType CollectionType { get { return ConfigurationElementCollectionType.AddRemoveClearMap; } } protected override ConfigurationElement CreateNewElement() { return new UrlConfigElement(); } protected override Object GetElementKey(ConfigurationElement element) { return ((UrlConfigElement)element).Name; } public UrlConfigElement this[int index] { get { return (UrlConfigElement)BaseGet(index); } set { if (BaseGet(index) != null) { BaseRemoveAt(index); } BaseAdd(index, value); } } new public UrlConfigElement this[string Name] { get { return (UrlConfigElement)BaseGet(Name); } } public int IndexOf(UrlConfigElement url) { return BaseIndexOf(url); } public void Add(UrlConfigElement url) { BaseAdd(url); } protected override void BaseAdd(ConfigurationElement element) { BaseAdd(element, false); } public void Remove(UrlConfigElement url) { if (BaseIndexOf(url) >= 0) BaseRemove(url.Name); } public void RemoveAt(int index) { BaseRemoveAt(index); } public void Remove(string name) { BaseRemove(name); } public void Clear() { BaseClear(); } } // Define the custom UrlsConfigElement elements that are contained // by the custom UrlsCollection. // Notice that you can change the default values to create new default elements. public class UrlConfigElement : ConfigurationElement { public UrlConfigElement(String name, String url) { this.Name = name; this.Url = url; } public UrlConfigElement() { this.Name = "Contoso"; this.Url = "http://www.contoso.com"; this.Port = 0; } [ConfigurationProperty("name", DefaultValue = "Contoso", IsRequired = true, IsKey = true)] public string Name { get { return (string)this["name"]; } set { this["name"] = value; } } [ConfigurationProperty("url", DefaultValue = "http://www.contoso.com", IsRequired = true)] [RegexStringValidator(@"\w+:\/\/[\w.]+\S*")] public string Url { get { return (string)this["url"]; } set { this["url"] = value; } } [ConfigurationProperty("port", DefaultValue = (int)0, IsRequired = false)] [IntegerValidator(MinValue = 0, MaxValue = 8080, ExcludeRange = false)] public int Port { get { return (int)this["port"]; } set { this["port"] = value; } } } VB 复制 Imports System.Configuration Friend Class UsingConfigurationCollectionAttribute ' Create a custom section and save it in the ' application configuration file. Private Shared Sub CreateCustomSection() Try ' Create a custom configuration section. Dim myUrlsSection As New UrlsSection() ' Get the current configuration file. Dim config As System.Configuration.Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None) ' Add the custom section to the application ' configuration file. If config.Sections("MyUrls") Is Nothing Then config.Sections.Add("MyUrls", myUrlsSection) End If ' Save the application configuration file. myUrlsSection.SectionInformation.ForceSave = True config.Save(ConfigurationSaveMode.Modified) Console.WriteLine("Created custom section in the application configuration file: {0}", config.FilePath) Console.WriteLine() Catch err As ConfigurationErrorsException Console.WriteLine("CreateCustomSection: {0}", err.ToString()) End Try End Sub Private Shared Sub ReadCustomSection() Try ' Get the application configuration file. Dim config As System.Configuration.Configuration = TryCast(ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None), Configuration) ' Read and display the custom section. Dim myUrlsSection As UrlsSection = TryCast(ConfigurationManager.GetSection("MyUrls"), UrlsSection) If myUrlsSection Is Nothing Then Console.WriteLine("Failed to load UrlsSection.") Else Console.WriteLine("URLs defined in app.config:") For i As Integer = 0 To myUrlsSection.Urls.Count - 1 Console.WriteLine(" Name={0} URL={1} Port={2}", myUrlsSection.Urls(i).Name, myUrlsSection.Urls(i).Url, myUrlsSection.Urls(i).Port) Next i End If Catch err As ConfigurationErrorsException Console.WriteLine("ReadCustomSection(string): {0}", err.ToString()) End Try End Sub Shared Sub Main(ByVal args() As String) ' Get the name of the application. Dim appName As String = Environment.GetCommandLineArgs()(0) ' Create a custom section and save it in the ' application configuration file. CreateCustomSection() ' Read the custom section saved in the ' application configuration file. ReadCustomSection() Console.WriteLine() Console.WriteLine("Enter any key to exit.") Console.ReadLine() End Sub End Class C# 复制 using System; using System.Configuration; class UsingConfigurationCollectionAttribute { // Create a custom section and save it in the // application configuration file. static void CreateCustomSection() { try { // Create a custom configuration section. UrlsSection myUrlsSection = new UrlsSection(); // Get the current configuration file. System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration( ConfigurationUserLevel.None); // Add the custom section to the application // configuration file. if (config.Sections["MyUrls"] == null) { config.Sections.Add("MyUrls", myUrlsSection); } // Save the application configuration file. myUrlsSection.SectionInformation.ForceSave = true; config.Save(ConfigurationSaveMode.Modified); Console.WriteLine("Created custom section in the application configuration file: {0}", config.FilePath); Console.WriteLine(); } catch (ConfigurationErrorsException err) { Console.WriteLine("CreateCustomSection: {0}", err.ToString()); } } static void ReadCustomSection() { try { // Get the application configuration file. System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration( ConfigurationUserLevel.None) as Configuration; // Read and display the custom section. UrlsSection myUrlsSection = ConfigurationManager.GetSection("MyUrls") as UrlsSection; if (myUrlsSection == null) Console.WriteLine("Failed to load UrlsSection."); else { Console.WriteLine("URLs defined in the configuration file:"); for (int i = 0; i < myUrlsSection.Urls.Count; i++) { Console.WriteLine(" Name={0} URL={1} Port={2}", myUrlsSection.Urls[i].Name, myUrlsSection.Urls[i].Url, myUrlsSection.Urls[i].Port); } } } catch (ConfigurationErrorsException err) { Console.WriteLine("ReadCustomSection(string): {0}", err.ToString()); } } static void Main(string[] args) { // Get the name of the application. string appName = Environment.GetCommandLineArgs()[0]; // Create a custom section and save it in the // application configuration file. CreateCustomSection(); // Read the custom section saved in the // application configuration file. ReadCustomSection(); Console.WriteLine(); Console.WriteLine("Enter any key to exit."); Console.ReadLine(); } }

using System;
using System.Configuration;


class UsingConfigurationCollectionAttribute
{

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

            // Create a custom configuration section.
            UrlsSection myUrlsSection = new UrlsSection();

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

            // Add the custom section to the application
            // configuration file.
            if (config.Sections["MyUrls"] == null)
            {
                config.Sections.Add("MyUrls", myUrlsSection);
            }


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

            Console.WriteLine("Created custom section in the application configuration file: {0}",
                config.FilePath);
            Console.WriteLine();

        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("CreateCustomSection: {0}", err.ToString());
        }

    }

    static void ReadCustomSection()
    {
        try
        {
            // Get the application configuration file.
            System.Configuration.Configuration config =
                    ConfigurationManager.OpenExeConfiguration(
                    ConfigurationUserLevel.None) as Configuration;

            // Read and display the custom section.
            UrlsSection myUrlsSection =
               ConfigurationManager.GetSection("MyUrls") as UrlsSection;

            if (myUrlsSection == null)
                Console.WriteLine("Failed to load UrlsSection.");
            else
            {
                Console.WriteLine("URLs defined in the configuration file:");
                for (int i = 0; i < myUrlsSection.Urls.Count; i++)
                {
                    Console.WriteLine("  Name={0} URL={1} Port={2}",
                        myUrlsSection.Urls[i].Name,
                        myUrlsSection.Urls[i].Url,
                        myUrlsSection.Urls[i].Port);
                }
            }

        }
        catch (ConfigurationErrorsException err)
        {
            Console.WriteLine("ReadCustomSection(string): {0}", err.ToString());
        }

    }

    static void Main(string[] args)
    {

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

        // Create a custom section and save it in the 
        // application configuration file.
        CreateCustomSection();

        // Read the custom section saved in the
        // application configuration file.
        ReadCustomSection();

        Console.WriteLine();
        Console.WriteLine("Enter any key to exit.");

        Console.ReadLine();
    }
}

继承层次结构

System.Object

System.Attribute

System.Configuration.ConfigurationCollectionAttribute

命名空间

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 系统要求。