ConfigurationProperty 类

定义

表示配置元素的一个特性或子级。Represents an attribute or a child of a configuration element. 此类不能被继承。This class cannot be inherited.

此 API 支持产品基础结构,不能在代码中直接使用。

public ref class ConfigurationProperty sealed
public sealed class ConfigurationProperty
type ConfigurationProperty = class
Public NotInheritable Class ConfigurationProperty
继承
ConfigurationProperty

示例

  1. 下面的代码示例演示如何在 ConfigurationProperty 创建自定义节时使用。The following code example shows how to use the ConfigurationProperty when you create a custom section.
using System;
using System.Configuration;
using System.Collections;
using System.ComponentModel;

namespace ConfigurationPropertyExample
{
    // Define a custom section.
    // Shows how to use the ConfigurationProperty
    // class when defining a custom section.
    public sealed class CustomSection : ConfigurationSection
    {
        // The collection (property bag) that contains 
        // the section properties.
        private static ConfigurationPropertyCollection _Properties;

        // The FileName property.
        private static ConfigurationProperty _FileName;

        // The Alias property.
        private static ConfigurationProperty _Alias;

        // The MaxUsers property.
        private static ConfigurationProperty _MaxUsers;

        // The MaxIdleTime property.
        private static ConfigurationProperty _MaxIdleTime;

        // CustomSection constructor.
        static CustomSection()
        {
            // Initialize the _FileName property
            _FileName =
                new ConfigurationProperty("fileName",
                typeof(string), "default.txt");

            // Initialize the _MaxUsers property
            _MaxUsers =
                new ConfigurationProperty("maxUsers",
                typeof(long), (long)1000,
                ConfigurationPropertyOptions.None);

            // Initialize the _MaxIdleTime property
            TimeSpan minTime = TimeSpan.FromSeconds(30);
            TimeSpan maxTime = TimeSpan.FromMinutes(5);

            ConfigurationValidatorBase _TimeSpanValidator =
                new TimeSpanValidator(minTime, maxTime, false);

            _MaxIdleTime =
                new ConfigurationProperty("maxIdleTime",
                typeof(TimeSpan), TimeSpan.FromMinutes(5),
                TypeDescriptor.GetConverter(typeof(TimeSpan)),
                _TimeSpanValidator,
                ConfigurationPropertyOptions.IsRequired,
                "[Description:This is the max idle time.]");

            // Initialize the _Alias property
            _Alias =
                new ConfigurationProperty("alias",
                typeof(string), "alias.txt");

            // Initialize the Property collection.
            _Properties = new ConfigurationPropertyCollection();
            _Properties.Add(_FileName);
            _Properties.Add(_Alias);
            _Properties.Add(_MaxUsers);
            _Properties.Add(_MaxIdleTime);
        }

        // Return the initialized property bag
        // for the configuration element.
        protected override ConfigurationPropertyCollection Properties
        {
            get
            {
                return _Properties;
            }
        }

        // Clear the property.
        public void ClearCollection()
        {
            Properties.Clear();
        }

        // Remove an element from the property collection.
        public void RemoveCollectionElement(string elName)
        {
            Properties.Remove(elName);
        }

        // Get the property collection enumerator.
        public IEnumerator GetCollectionEnumerator()
        {
            return (Properties.GetEnumerator());
        }

        [StringValidator(InvalidCharacters = " ~!@#$%^&*()[]{}/;'\"|\\",
            MinLength = 1, MaxLength = 60)]
        public string FileName
        {
            get
            {
                return (string)this["fileName"];
            }
            set
            {
                this["fileName"] = value;
            }
        }

        [StringValidator(InvalidCharacters = " ~!@#$%^&*()[]{}/;'\"|\\",
            MinLength = 1, MaxLength = 60)]
        public string Alias
        {
            get
            {
                return (string)this["alias"];
            }
            set
            {
                this["alias"] = value;
            }
        }

        [LongValidator(MinValue = 1, MaxValue = 1000000,
            ExcludeRange = false)]
        public long MaxUsers
        {
            get
            {
                return (long)this["maxUsers"];
            }
            set
            {
                this["maxUsers"] = value;
            }
        }

        public TimeSpan MaxIdleTime
        {
            get
            {
                return (TimeSpan)this["maxIdleTime"];
            }
            set
            {
                this["maxIdleTime"] = value;
            }
        }
    }
}
Imports System.Configuration
Imports System.Collections
Imports System.ComponentModel

' Define a custom section.
' Shows how to use the ConfigurationProperty
' class when defining a custom section.
Public NotInheritable Class CustomSection
    Inherits ConfigurationSection

    ' The collection (property bag) that contains 
    ' the section properties.
    Private Shared _Properties As ConfigurationPropertyCollection

    ' The FileName property.
    Private Shared _FileName As ConfigurationProperty

    ' The Alias property.
    Private Shared _Alias As ConfigurationProperty

    ' The MasUsers property.
    Private Shared _MaxUsers As ConfigurationProperty

    ' The MaxIdleTime property.
    Private Shared _MaxIdleTime As ConfigurationProperty

    ' CustomSection constructor.
    Shared Sub New()

        ' Initialize the _FileName property
        _FileName = New ConfigurationProperty( _
            "fileName", GetType(String), "default.txt")

        ' Initialize the _MaxUsers property
        _MaxUsers = New ConfigurationProperty( _
            "maxUsers", GetType(Long), 1000L, _
            ConfigurationPropertyOptions.None)

        ' Initialize the _MaxIdleTime property
        Dim minTime As TimeSpan = TimeSpan.FromSeconds(30)
        Dim maxTime As TimeSpan = TimeSpan.FromMinutes(5)
        Dim _TimeSpanValidator = _
            New TimeSpanValidator(minTime, maxTime, False)

        _MaxIdleTime = New ConfigurationProperty( _
            "maxIdleTime", GetType(TimeSpan), _
            TimeSpan.FromMinutes(5), _
            TypeDescriptor.GetConverter(GetType(TimeSpan)), _
            _TimeSpanValidator, _
            ConfigurationPropertyOptions.IsRequired, _
            "[Description:This is the max idle time.]")

        ' Initialize the _Alias property
        _Alias = New ConfigurationProperty( _
            "alias", GetType(String), "alias.txt")

        ' Property collection initialization.
        ' The collection (property bag) that contains 
        ' the properties is declared as:
        ' ConfigurationPropertyCollection _Properties;
        _Properties = New ConfigurationPropertyCollection()
        _Properties.Add(_FileName)
        _Properties.Add(_Alias)
        _Properties.Add(_MaxUsers)
        _Properties.Add(_MaxIdleTime)

    End Sub

    ' Return the initialized property bag
    ' for the configuration element.
    Protected Overrides ReadOnly Property Properties() _
    As ConfigurationPropertyCollection
        Get
            Return _Properties
        End Get
    End Property

    <StringValidator(InvalidCharacters:= _
    " ~!@#$%^&*()[]{}/;'""|\", MinLength:=1, _
    MaxLength:=60)> _
    Public Property FileName() As String
        Get
            Return CStr(Me("fileName"))
        End Get
        Set(ByVal value As String)
            Me("fileName") = value
        End Set
    End Property

    <StringValidator(InvalidCharacters:= _
    " ~!@#$%^&*()[]{}/;'""|\", MinLength:=1, _
    MaxLength:=60)> _
    Public Property [Alias]() As String
        Get
            Return CStr(Me("alias"))
        End Get
        Set(ByVal value As String)
            Me("alias") = value
        End Set
    End Property

    <LongValidator(MinValue:=1, _
    MaxValue:=1000000, ExcludeRange:=False)> _
    Public Property MaxUsers() As Long
        Get
            Return Fix(Me("maxUsers"))
        End Get
        Set(ByVal value As Long)
            Me("maxUsers") = value
        End Set
    End Property

    Public Property MaxIdleTime() As TimeSpan
        Get
            Return CType(Me("maxIdleTime"), TimeSpan)
        End Get
        Set(ByVal value As TimeSpan)
            Me("maxIdleTime") = value
        End Set
    End Property
End Class

下面是上一示例中的代码所使用的配置文件的摘录。The following is an excerpt of the configuration file used by the code in the previous example.

<configuration>
  <configSections>
    <section name="CustomSection" type="ConfigurationPropertyExample.CustomSection, ConfigurationPropertyExample" 
      allowDefinition="Everywhere" allowExeDefinition="MachineToApplication" 
      restartOnExternalChanges="true" />
  </configSections>
  <CustomSection fileName="override.txt" alias="alias.txt" 
    maxUsers="1000" maxIdleTime="00:05:00" />
</configuration>

下面的示例演示如何在代码中创建上一个节。The following example shows how to create the previous section in code.

// Define a custom section programmatically.
static void CreateSection()
{
    try
    {
        CustomSection customSection;

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

        // Create the section entry  
        // in the <configSections> and the 
        // related target section in <configuration>.
        // Call it "CustomSection2" since the file in this 
        // example already has "CustomSection".
        if (config.Sections["CustomSection"] == null)
        {
            customSection = new CustomSection();
            config.Sections.Add("CustomSection2", customSection);
            customSection.SectionInformation.ForceSave = true;
            config.Save(ConfigurationSaveMode.Full);
        }
    }
    catch (ConfigurationErrorsException err)
    {
        Console.WriteLine(err.ToString());
    }
}
' Create a custom section.
Shared Sub CreateSection()
    Try
        Dim customSection As CustomSection

        ' Get the current configuration file.
        Dim config As System.Configuration.Configuration = _
            ConfigurationManager.OpenExeConfiguration( _
            ConfigurationUserLevel.None)

        ' Create the section entry  
        ' in the <configSections> and the 
        ' related target section in <configuration>.
        ' Since the config file already has "CustomSection",
        ' call this one "CustomSection2".
        If config.Sections("CustomSection") Is Nothing Then
            customSection = New CustomSection()
            config.Sections.Add("CustomSection", customSection)
            customSection.SectionInformation.ForceSave = True
            config.Save(ConfigurationSaveMode.Full)
        End If
    Catch err As ConfigurationErrorsException
        Console.WriteLine(err.ToString())
    End Try
End Sub

注解

对于简单的 ConfigurationElement ,如 CustomSection 下一个示例中所示, ConfigurationProperty 对象表示属性(如) fileNameIn the case of a simple ConfigurationElement, such as the CustomSection shown in the next example, the ConfigurationProperty objects represent attributes such as fileName.

对于更复杂的配置元素(例如包含子节的部分), authentication ConfigurationProperty 对象可以表示 ConfigurationElement 对象以及属性。In the case of more complex configuration elements such as a section containing subsections, for instance authentication, the ConfigurationProperty objects can represent ConfigurationElement objects as well as attributes.

ConfigurationPropertyCollection类表示对象的集合,这些 ConfigurationProperty 对象可以是属性或 ConfigurationElement 配置元素的对象。The ConfigurationPropertyCollection class represents the collection of the ConfigurationProperty objects that can be either attributes or ConfigurationElement objects of a configuration element.

ConfigurationProperty类表示单独的配置设置。The ConfigurationProperty class represents an individual configuration setting. 此类允许你获取或设置特定配置实体(特性或元素)的名称、类型和默认值,并指定属性是必需的,是元素键,还是表示默认元素集合。This class allows you to get or set the name, type, and default value for a particular configuration entity (attribute or element) and specify whether the attribute is required, is an element key, or represents a default element collection.

继承者说明

每个 ConfigurationElement 对象都创建 ConfigurationPropertyCollection ConfigurationProperty 对象的内部集合,这些对象表示元素特性或子元素的集合。Every ConfigurationElement object creates an internal ConfigurationPropertyCollection collection of ConfigurationProperty objects that represents either the element attributes or a collection of child elements.

不可自定义的信息和功能由 ElementInformation 属性提供的对象所包含 ElementInformationNon-customizable information and functionality is contained by an ElementInformation object provided by the ElementInformation property.

可以使用编程方式或声明性(特性化)编码模型创建自定义配置元素。You can use a programmatic or a declarative (attributed) coding model to create a custom configuration element.

-编程模型。- Programmatic Model. 此模型要求您为每个元素特性创建一个属性,以获取和/或设置其值并将其添加到基础基类的内部属性包 ConfigurationElementThis model requires that you create a property for each element attribute to get and/or set its value and add it to the internal property bag of the underlying ConfigurationElement base class.

-声明性模型。- Declarative Model. 这种简单的模型(也称为特性化模型)允许您通过使用属性来定义元素特性,并使用特性修饰它。This simpler model, also called attributed model, allows you to define an element attribute by using a property and decorate it with attributes. 这些属性指示 ASP.NET 配置系统有关属性类型及其默认值的信息。These attributes instruct the ASP.NET configuration system about the property types and their default values. 通过反射获取此信息,ASP.NET 配置系统会为您创建元素属性对象并执行所需的初始化。With this information, obtained through reflection, the ASP.NET configuration system creates the element property objects for you and performs the required initialization.

构造函数

ConfigurationProperty(String, Type)

此 API 支持产品基础结构,不能在代码中直接使用。

初始化 ConfigurationProperty 类的新实例。Initializes a new instance of the ConfigurationProperty class.

ConfigurationProperty(String, Type, Object)

此 API 支持产品基础结构,不能在代码中直接使用。

初始化 ConfigurationProperty 类的新实例。Initializes a new instance of the ConfigurationProperty class.

ConfigurationProperty(String, Type, Object, ConfigurationPropertyOptions)

此 API 支持产品基础结构,不能在代码中直接使用。

初始化 ConfigurationProperty 类的新实例。Initializes a new instance of the ConfigurationProperty class.

ConfigurationProperty(String, Type, Object, TypeConverter, ConfigurationValidatorBase, ConfigurationPropertyOptions)

此 API 支持产品基础结构,不能在代码中直接使用。

初始化 ConfigurationProperty 类的新实例。Initializes a new instance of the ConfigurationProperty class.

ConfigurationProperty(String, Type, Object, TypeConverter, ConfigurationValidatorBase, ConfigurationPropertyOptions, String)

此 API 支持产品基础结构,不能在代码中直接使用。

初始化 ConfigurationProperty 类的新实例。Initializes a new instance of the ConfigurationProperty class.

属性

Converter

此 API 支持产品基础结构,不能在代码中直接使用。

获取 TypeConverter,该转换器用于将此 ConfigurationProperty 转换为便于写入配置文件的 XML 表示形式。Gets the TypeConverter used to convert this ConfigurationProperty into an XML representation for writing to the configuration file.

DefaultValue

此 API 支持产品基础结构,不能在代码中直接使用。

获取此 ConfigurationProperty 属性的默认值。Gets the default value for this ConfigurationProperty property.

Description

此 API 支持产品基础结构,不能在代码中直接使用。

获取与 ConfigurationProperty 关联的说明。Gets the description associated with the ConfigurationProperty.

IsAssemblyStringTransformationRequired

此 API 支持产品基础结构,不能在代码中直接使用。

指示在针对早期版本的 .NET Framework.NET Framework 序列化配置属性时,是否需要转换该属性的程序集名称。Indicates whether the assembly name for the configuration property requires transformation when it is serialized for an earlier version of the .NET Framework.NET Framework.

IsDefaultCollection

此 API 支持产品基础结构,不能在代码中直接使用。

获取一个值,该值指示属性是否为默认的元素集合。Gets a value that indicates whether the property is the default collection of an element.

IsKey

此 API 支持产品基础结构,不能在代码中直接使用。

获取一个值,该值指示此 ConfigurationProperty 是否为 ConfigurationElement 包含对象的键。Gets a value indicating whether this ConfigurationProperty is the key for the containing ConfigurationElement object.

IsRequired

此 API 支持产品基础结构,不能在代码中直接使用。

获取一个值,该值指示此 ConfigurationProperty 是否为必需的。Gets a value indicating whether this ConfigurationProperty is required.

IsTypeStringTransformationRequired

此 API 支持产品基础结构,不能在代码中直接使用。

指示在针对早期版本的 .NET Framework.NET Framework 序列化配置属性时,是否需要转换该属性的类型名称。Indicates whether the type name for the configuration property requires transformation when it is serialized for an earlier version of the .NET Framework.NET Framework.

IsVersionCheckRequired

此 API 支持产品基础结构,不能在代码中直接使用。

指示进行序列化时是否应查询配置属性的父配置节,以确定是否应将配置属性序列化到 XML 中。Indicates whether the configuration property's parent configuration section is queried at serialization time to determine whether the configuration property should be serialized into XML.

Name

此 API 支持产品基础结构,不能在代码中直接使用。

获取此 ConfigurationProperty 的名称。Gets the name of this ConfigurationProperty.

Type

此 API 支持产品基础结构,不能在代码中直接使用。

获取此 ConfigurationProperty 对象的类型。Gets the type of this ConfigurationProperty object.

Validator

此 API 支持产品基础结构,不能在代码中直接使用。

获取 ConfigurationValidatorAttribute,它用于验证此 ConfigurationProperty 对象。Gets the ConfigurationValidatorAttribute, which is used to validate this ConfigurationProperty object.

方法

Equals(Object)

确定指定对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(继承自 Object)

适用于

另请参阅