ConfigurationElement 類別

定義

表示組態檔內的組態項目。

public ref class ConfigurationElement abstract
public abstract class ConfigurationElement
type ConfigurationElement = class
Public MustInherit Class ConfigurationElement
繼承
ConfigurationElement
衍生

範例

下列程式代碼範例示範如何在自定義區段中實作自定義 ConfigurationElement 專案,以及實作為自定義區段中專案的集合。 此範例包含下列檔案:

  • app.config 檔案,其中包含名為 MyUrls的自定義區段。 本節包含簡單的元素, (它不包含任何其他元素) 和元素集合。 簡單項目的名稱為 simple ,且集合名為 urls

  • 主控台應用程式。 應用程式會讀取 app.config 檔案的內容,並將資訊寫入主控台。 它會使用衍生自 ConfigurationElementConfigurationElementCollection和的 ConfigurationSection類別。

  • 名為 UrlsSection 的類別,衍生自 ConfigurationSection 類別。 這個類別可用來存取組態檔中的 區 MyUrls 段。

  • 名為 UrlsCollection 的類別,衍生自 ConfigurationElementCollection 類別。 這個類別可用來存取 urls 組態檔中的集合。

  • 名為 UrlConfigElement 的類別,衍生自 ConfigurationElement 類別。 這個類別可用來存取 simple 組態檔中集合的 urls 元素和成員。

若要執行範例,請執行下列步驟:

  1. 建立具有主控台應用程式項目的解決方案,以及名為 ConfigurationElement的類別庫專案。

  2. 將三個類別檔案放在類別庫專案中,並將其他檔案放在主控台連結庫專案中。

  3. 在這兩個專案中,都會設定 的 System.Configuration參考。

  4. 在主控台應用程式專案中,設定類別庫專案的項目參考。

// 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();
        }
    }
}
' Set Assembly name to ConfigurationElement
' and set Root namespace to Samples.AspNet
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
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 <simple .... />.
        [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
        // <urls> <add .../> </urls> 
        // Note: the "IsDefaultCollection = false" 
        // instructs the .NET Framework to build a nested 
        // section like <urls> ...</urls>.
        [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;
        }
    }
}
Imports System.Configuration
Imports System.Collections

' Define a custom section containing an individual
' element and a collection of elements.
Public Class UrlsSection
    Inherits ConfigurationSection

    <ConfigurationProperty("name", _
        DefaultValue:="MyFavorites", _
        IsRequired:=True, _
        IsKey:=False), _
        StringValidator( _
        InvalidCharacters:=" ~!@#$%^&*()[]{}/;'""|\", _
        MinLength:=1, MaxLength:=60)> _
        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 <simple .... />.
    <ConfigurationProperty("simple")> _
        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
    ' <urls> <add .../> </urls> 
    ' Note: the "IsDefaultCollection = false" 
    ' instructs the .NET Framework to build a nested 
    ' section like <urls> ...</urls>.
    <ConfigurationProperty("urls", _
        IsDefaultCollection:=False)> _
        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

    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
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.ClearElementName = 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.
        }
    }
}
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

    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.ClearElementName = 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

    Protected Overrides Sub BaseAdd( _
    ByVal element As ConfigurationElement)
        BaseAdd(element, False)
        ' Add custom code here.
    End Sub

    Public Overloads 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 Overloads Sub Remove(ByVal name As String)
        BaseRemove(name)
    End Sub

    Public Sub Clear()
        BaseClear()
    End Sub
End Class
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;
        }
    }
}
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

    ' Default constructor, will use default values as defined
    Public Sub New()

    End Sub


    ' 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


    <ConfigurationProperty("name", _
        DefaultValue:="Microsoft", _
        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.microsoft.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:=0, _
        IsRequired:=False), _
        IntegerValidator(MinValue:=0, _
        MaxValue:=8080, ExcludeRange:=False)> _
        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

    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

備註

ConfigurationElement是抽象類,用來代表組態檔中的 XML 元素, (例如 Web.config) 。 組態檔中的專案可以包含零、一或多個子元素。

因為類別 ConfigurationElement 定義為抽象,所以您無法建立它的實例。 您只能從中衍生類別。 .NET Framework 包含衍生自 類別的ConfigurationElement類別,以表示標準 XML 組態專案,例如 ConfigurationSection。 您也可以擴充 類別,以存取自定義組 ConfigurationElement 態專案和區段。 本主題稍後包含的範例示範如何使用衍生自 ConfigurationElement的自定義類別來存取自定義組態專案和區段。

您也可以擴充標準組態類型,例如 ConfigurationElementConfigurationElementCollectionConfigurationPropertyConfigurationSection。 如需詳細資訊,請參閱這些類別的檔。

如需如何存取組態檔中資訊的詳細資訊,請參閱 ConfigurationManager 類別和 WebConfigurationManager 類別。

給實施者的注意事項

每個 ConfigurationElement 物件都會建立代表項目屬性或子專案集合的物件內部 ConfigurationPropertyCollection 集合 ConfigurationProperty

不可自訂的資訊和功能是由 ElementInformation 屬性所提供的 ElementInformation 物件所包含。

您可以使用程式設計或宣告式 (屬性化) 編碼模型來建立自訂組態專案:

  • 程序設計模型需要針對每個元素屬性建立屬性,以取得或設定其值,並將它新增至基礎 ConfigurationElement 基類的內部屬性包。 如需如何使用此模型的範例,請參閱 類別 ConfigurationSection

  • 更簡單的宣告式模型也稱為屬性模型,可讓您使用 屬性來定義元素屬性,然後使用屬性裝飾它。 這些屬性會指示 ASP.NET 組態系統屬性類型及其預設值。 透過反映取得這項資訊,ASP.NET 組態系統會為您建立元素屬性物件,並執行必要的初始化。 本主題稍後所示的範例示範如何使用此模型。

建構函式

ConfigurationElement()

初始化 ConfigurationElement 類別的新執行個體。

屬性

CurrentConfiguration

取得最上層 Configuration 執行個體的參考,這個執行個體表示目前 ConfigurationElement 執行個體所屬的組態階層架構。

ElementInformation

取得 ElementInformation 物件,其中包含 ConfigurationElement 物件之不可自訂的資訊和功能。

ElementProperty

取得表示 ConfigurationElementProperty 物件本身的 ConfigurationElement 物件。

EvaluationContext

取得 ConfigurationElement 物件的 ContextInformation 物件。

HasContext

取得值,指出 CurrentConfiguration 屬性是否為 null

Item[ConfigurationProperty]

取得或設定此組態項目的屬性 (Property) 或屬性 (Attribute)。

Item[String]

取得或設定此一組態項目的屬性或子項目。

LockAllAttributesExcept

取得已鎖定屬性的集合。

LockAllElementsExcept

取得已鎖定項目的集合。

LockAttributes

取得已鎖定屬性的集合。

LockElements

取得已鎖定項目的集合。

LockItem

取得或設定值,指出此項目是否已被鎖定。

Properties

取得屬性的集合。

方法

DeserializeElement(XmlReader, Boolean)

從組態檔讀取 XML。

Equals(Object)

將目前的 ConfigurationElement 執行個體與指定的物件相比較。

GetHashCode()

取得表示目前 ConfigurationElement 執行個體的唯一值。

GetTransformedAssemblyString(String)

傳回指定之組件名稱的轉換版本。

GetTransformedTypeString(String)

傳回指定之型別名稱的轉換版本。

GetType()

取得目前執行個體的 Type

(繼承來源 Object)
Init()

ConfigurationElement 物件設定為它的初始狀態。

InitializeDefault()

用來初始化 ConfigurationElement 物件的預設值集。

IsModified()

在衍生類別中進行實作時,指出這個組態項目自上次儲存或載入後是否已修改。

IsReadOnly()

取得值,這個值表示 ConfigurationElement 物件是否唯讀。

ListErrors(IList)

將這個 ConfigurationElement 物件中和所有子項目中的無效屬性錯誤加入傳遞的清單。

MemberwiseClone()

建立目前 Object 的淺層複製。

(繼承來源 Object)
OnDeserializeUnrecognizedAttribute(String, String)

取得值,指出在還原序列化程序中是否遇到未知的屬性 (Attribute)。

OnDeserializeUnrecognizedElement(String, XmlReader)

取得值,指出在還原序列化程序中是否遇到未知的項目。

OnRequiredPropertyNotFound(String)

在找不到必要的屬性時擲回例外狀況 (Exception)。

PostDeserialize()

還原序列化之後呼叫。

PreSerialize(XmlWriter)

序列化之前呼叫。

Reset(ConfigurationElement)

重設 ConfigurationElement 物件的內部狀態,包括鎖定和屬性的集合。

ResetModified()

在衍生類別中實作時,將 IsModified() 方法的值重設為 false

SerializeElement(XmlWriter, Boolean)

在衍生類別中實作時,將此組態項目的內容寫入組態檔中。

SerializeToXmlElement(XmlWriter, String)

在衍生類別中實作時,將此組態項目的外部標記寫入組態檔中。

SetPropertyValue(ConfigurationProperty, Object, Boolean)

將屬性設定為指定的值。

SetReadOnly()

設定 IsReadOnly() 物件和所有子項目的 ConfigurationElement 屬性。

ToString()

傳回代表目前物件的字串。

(繼承來源 Object)
Unmerge(ConfigurationElement, ConfigurationElement, ConfigurationSaveMode)

修改 ConfigurationElement 物件,以移除不應該儲存的所有值。

適用於

另請參閱