Il presente articolo è stato tradotto automaticamente. Passare il puntatore sulle frasi nell'articolo per visualizzare il testo originale. Ulteriori informazioni.
Traduzione
Originale
Questo argomento non è stato ancora valutato - Valuta questo argomento

Classe ConfigurationElement

Rappresenta un elemento di configurazione all'interno di un file di configurazione.

System.Object
  System.Configuration.ConfigurationElement
    Ulteriori informazioni

Spazio dei nomi:  System.Configuration
Assembly:  System.Configuration (in System.Configuration.dll)
public abstract class ConfigurationElement

Il tipo ConfigurationElement espone i seguenti membri.

  NomeDescrizione
Metodo protettoConfigurationElementInizializza una nuova istanza di ConfigurationElement classe.
In alto
  NomeDescrizione
Proprietà pubblicaCurrentConfigurationOttiene un riferimento al livello superiore Configuration istanza di che rappresenta la gerarchia di configurazione che l'oggetto corrente ConfigurationElement l'istanza appartiene.
Proprietà pubblicaElementInformationottiene ElementInformation oggetto contenente informazioni e funzionalità non personalizzabili di ConfigurationElement oggetto.
Proprietà protetta.ElementPropertyottiene ConfigurationElementProperty oggetto che rappresenta ConfigurationElement obiettar.
Proprietà protetta.EvaluationContextottiene ContextInformation oggetto per ConfigurationElement oggetto.
Proprietà protetta.HasContextottiene un valore che indica se CurrentConfiguration la proprietà è null.
Proprietà protetta.Item[ConfigurationProperty]Ottiene o imposta una proprietà o un attributo di questo elemento di configurazione.
Proprietà protetta.Item[String]ottiene o imposta una proprietà, un attributo, o un elemento figlio di questo elemento di configurazione.
Proprietà pubblicaLockAllAttributesExceptottiene la raccolta di attributi bloccati.
Proprietà pubblicaLockAllElementsExceptottiene la raccolta di elementi bloccati.
Proprietà pubblicaLockAttributesottiene la raccolta di attributi bloccati
Proprietà pubblicaLockElementsottiene la raccolta di elementi bloccati.
Proprietà pubblicaLockItemOttiene o imposta un valore che indica se l'elemento è bloccato.
Proprietà protetta.Propertiesottiene la raccolta di proprietà.
In alto
  NomeDescrizione
Metodo protettoDeserializeElementLegge XML dal file di configurazione.
Metodo pubblicoEqualsconfronta la corrente ConfigurationElement istanza all'oggetto specificato. (Esegue l'override di Object.Equals(Object)).
Metodo protettoFinalize Consente a un oggetto di provare a liberare risorse ed eseguire altre operazioni di pulizia prima che l'oggetto stesso venga reclamato dalla procedura di Garbage Collection. (Ereditato da Object)
Metodo pubblicoGetHashCodeOttiene un valore univoco che rappresenta l'oggetto corrente ConfigurationElement istanza. (Esegue l'override di Object.GetHashCode()).
Metodo protettoGetTransformedAssemblyStringRestituisce la versione trasformata con il nome specificato dell'assembly.
Metodo protettoGetTransformedTypeStringRestituisce la versione trasformata il nome del tipo specificato.
Metodo pubblicoGetType Ottiene il Type dell'istanza corrente. (Ereditato da Object)
Metodo protettoInitimposta ConfigurationElement oggetto allo stato iniziale.
Metodo protettoInitializeDefaultUtilizzato per inizializzare una serie di valori per ConfigurationElement oggetto.
Metodo protettoIsModifiedIndica se questo elemento di configurazione è stato modificato dall'ultima volta in cui è stato salvato o caricato stato, quando implementato in una classe derivata.
Metodo pubblicoIsReadOnlyottiene un valore che indica se ConfigurationElement l'oggetto è di sola lettura.
Metodo protettoListErrorsAggiunge gli errori non di valido-proprietà in questa ConfigurationElement l'oggetto e in tutti i sottoelementi, all'elenco passato.
Metodo protettoMemberwiseCloneConsente di creare una copia dei riferimenti dell'oggetto Object corrente. (Ereditato da Object)
Metodo protettoOnDeserializeUnrecognizedAttributeOttiene un valore che indica se un attributo sconosciuto viene rilevato durante la deserializzazione.
Metodo protettoOnDeserializeUnrecognizedElementOttiene un valore che indica se un elemento non viene rilevato durante la deserializzazione.
Metodo protettoOnRequiredPropertyNotFoundGenera un'eccezione quando una proprietà richiesta non viene trovata.
Metodo protettoPostDeserializeChiamata dopo la deserializzazione.
Metodo protettoPreSerializeChiamata prima della serializzazione.
Metodo protettoResetReimposta lo stato interno di ConfigurationElement oggetto, inclusi i blocchi e le raccolte di proprietà.
Metodo protettoResetModifiedReimposta il valore di IsModified metodo su false quando implementato in una classe derivata.
Metodo protettoSerializeElementScrive il contenuto di questo elemento di configurazione nel file di configurazione quando implementato in una classe derivata.
Metodo protettoSerializeToXmlElementScrive i tag all'esterno dell'elemento di configurazione nel file di configurazione quando implementato in una classe derivata.
Metodo protettoSetPropertyValueImposta una proprietà sul valore specificato.
Metodo protettoSetReadOnlyimposta IsReadOnly proprietà di ConfigurationElement oggetto e tutti i sottoelementi.
Metodo pubblicoToString Restituisce una stringa che rappresenta l'oggetto corrente. (Ereditato da Object)
Metodo protettoUnmergemodifica ConfigurationElement oggetto per rimuovere tutti i valori che non devono essere salvati.
In alto

ConfigurationElement è una classe astratta che viene utilizzata per rappresentare un elemento XML in un file di configurazione (come Web.config). Un elemento in un file di configurazione può contenere zero, uno, o altri elementi figlio.

Poiché ConfigurationElement la classe è definita come abstract, non è possibile creare un'istanza. È possibile derivare solo le classi da. .NET Framework include classi che derivano da ConfigurationElement classe per rappresentare gli elementi di configurazione standard XML, ad esempio ConfigurationSection. È anche possibile estendere ConfigurationElement classe per accedere agli elementi di configurazione personalizzati e le sezioni. Nell'esempio incluso più avanti in questo argomento viene illustrato come accedere agli elementi di configurazione personalizzati e le sezioni tramite le classi personalizzate che derivano da ConfigurationElement.

È anche possibile estendere i tipi standard di configurazione come ConfigurationElement, ConfigurationElementCollection, ConfigurationPropertye ConfigurationSection. Per ulteriori informazioni, vedere la documentazione per tali classi.

Per ulteriori informazioni su come accedere alle informazioni contenute nei file di configurazione, vedere ConfigurationManager classe e WebConfigurationManager classe.

Note per gli eredi

ogni ConfigurationElement l'oggetto crea un inner ConfigurationPropertyCollection raccolta di ConfigurationProperty oggetti che rappresenta gli attributi dell'elemento o una raccolta di elementi figlio.

le informazioni e funzionalità Non personalizzabili sono contenute da ElementInformation oggetto fornito da ElementInformation proprietà.

È possibile utilizzare un modello (con) a livello di codice o dichiarativo di codifica per creare un elemento di configurazione personalizzato:

  • Il modello a livello di codice è necessario che per ogni attributo dell'elemento, creare una proprietà per ottenere o impostare il valore e aggiungerlo al contenitore di proprietà interno dell'oggetto sottostante ConfigurationElement classe base. per un esempio di come utilizzare questo modello, vedere ConfigurationSection classe.

  • Il modello dichiarativo più semplice, anche noto come modello con attributi, consente di definire un attributo dell'elemento utilizzando una proprietà e quindi lo decoriate con attributi. Questi attributi indicano al sistema di configurazione ASP.NET sui tipi di proprietà e i relativi valori predefiniti. Con queste informazioni, ottenute tramite reflection, il sistema di configurazione ASP.NET crea oggetti della proprietà dell'elemento per l'utente che esegue l'inizializzazione necessaria. Nell'esempio illustrato più avanti in questo argomento viene illustrato come utilizzare questo modello.

Nell'esempio di codice seguente viene illustrato come implementare una classe personalizzata ConfigurationElement entrambi come singolo elemento in una sezione personalizzata e come una raccolta di elementi in una sezione personalizzata. L'esempio è costituito dai seguenti file:

  • Un file app.config contenente una sezione personalizzata denominata MyUrls. Questa sezione contiene un elemento semplice (non contiene altri elementi) e una raccolta di elementi. l'elemento semplice è denominato simple e la raccolta è denominata urls.

  • un'applicazione console. L'applicazione legge il contenuto del file app.config e scrive le informazioni nella console. Utilizza le classi che derivano da ConfigurationElement, ConfigurationElementCollectione ConfigurationSection.

  • Classe denominata UrlsSection che deriva da ConfigurationSection classe. Questa classe viene utilizzata per accedere a MyUrls sezione nel file di configurazione.

  • Classe denominata UrlsCollection che deriva da ConfigurationElementCollection classe. Questa classe viene utilizzata per accedere a urls raccolta nel file di configurazione.

  • Classe denominata UrlConfigElement che deriva da ConfigurationElement classe. Questa classe viene utilizzata per accedere a simple elemento e membri di urls raccolta nel file di configurazione.

Per eseguire l'esempio, effettuare i passaggi seguenti:

  1. Creare una soluzione contenente un progetto di libreria del progetto e una classe di applicazione console denominato ConfigurationElement.

  2. Inserire i tre file della classe nel progetto Libreria di classi e inserire gli altri file nel progetto di libreria della console.

  3. In entrambi i progetti impostati un riferimento a System.Configuration.

  4. Nel progetto di applicazione console impostare un riferimento al progetto Libreria di classi.


<configuration>
	<configSections>
		<section name="MyUrls" type="Samples.AspNet.UrlsSection, ConfigurationElement, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" allowDefinition="Everywhere" allowExeDefinition="MachineToApplication" restartOnExternalChanges="true" />
	</configSections>
	<MyUrls name="MyFavorites">
    <simple name="Microsoft1" url="http://www.microsoft1.com" port="1" />
    <urls>
      <clear />
      <add name="Microsoft2" url="http://www.microsoft2.com" port="2" />
      <add name="Contoso" url="http://www.contoso.com" port="8080" />
    </urls>
	</MyUrls>
</configuration>



' 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



// 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();
        }
    }
}



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

    <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 '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 



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
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.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 '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



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
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


    <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 '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 




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;
        }
    }
}


.NET Framework

Supportato in: 4.5, 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supportato in: 4, 3.5 SP1

Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (ruoli di base del server non supportati), Windows Server 2008 R2 (ruoli di base del server supportati con SP1 o versione successiva, Itanium non supportato)

.NET Framework non supporta tutte le versioni di ciascuna piattaforma. Per un elenco delle versioni supportate, vedere Requisiti di sistema di .NET Framework.
Qualsiasi membro static (Shared in Visual Basic) pubblico di questo tipo è thread-safe. I membri di istanza non sono garantiti come thread-safe.
System.Object
  System.Configuration.ConfigurationElement
    System.Configuration.ConfigurationElementCollection
    System.Configuration.ConfigurationSection
    System.Configuration.ConnectionStringSettings
    System.Configuration.IdnElement
    System.Configuration.IriParsingElement
    System.Configuration.KeyValueConfigurationElement
    System.Configuration.NameValueConfigurationElement
    System.Configuration.ProtectedProviderSettings
    System.Configuration.ProviderSettings
    System.Configuration.SchemeSettingElement
    System.Configuration.SettingElement
    System.Configuration.SettingValueElement
    System.Data.Services.Configuration.DataServicesReplaceFunctionFeature
    System.IdentityModel.Configuration.AudienceUriElement
    System.IdentityModel.Configuration.ConfigurationElementInterceptor
    System.IdentityModel.Configuration.IdentityConfigurationElement
    System.IdentityModel.Configuration.IdentityModelCachesElement
    System.IdentityModel.Configuration.SecurityTokenHandlerConfigurationElement
    System.IdentityModel.Configuration.TokenReplayDetectionElement
    System.IdentityModel.Configuration.X509CertificateValidationElement
    System.IdentityModel.Services.ChunkedCookieHandlerElement
    System.IdentityModel.Services.Configuration.FederationConfigurationElement
    System.IdentityModel.Services.Configuration.WSFederationElement
    System.IdentityModel.Services.CookieHandlerElement
    System.IdentityModel.Services.ServiceCertificateElement
    System.Net.Configuration.AuthenticationModuleElement
    System.Net.Configuration.BypassElement
    System.Net.Configuration.ConnectionManagementElement
    System.Net.Configuration.FtpCachePolicyElement
    System.Net.Configuration.HttpCachePolicyElement
    System.Net.Configuration.HttpListenerElement
    System.Net.Configuration.HttpListenerTimeoutsElement
    System.Net.Configuration.HttpWebRequestElement
    System.Net.Configuration.Ipv6Element
    System.Net.Configuration.ModuleElement
    System.Net.Configuration.PerformanceCountersElement
    System.Net.Configuration.ProxyElement
    System.Net.Configuration.ServicePointManagerElement
    System.Net.Configuration.SmtpNetworkElement
    System.Net.Configuration.SmtpSpecifiedPickupDirectoryElement
    System.Net.Configuration.SocketElement
    System.Net.Configuration.WebProxyScriptElement
    System.Net.Configuration.WebRequestModuleElement
    System.Net.Configuration.WebUtilityElement
    System.Runtime.Caching.Configuration.MemoryCacheElement
    System.Runtime.Serialization.Configuration.DeclaredTypeElement
    System.Runtime.Serialization.Configuration.ParameterElement
    System.Runtime.Serialization.Configuration.TypeElement
    System.Security.Authentication.ExtendedProtection.Configuration.ExtendedProtectionPolicyElement
    System.Security.Authentication.ExtendedProtection.Configuration.ServiceNameElement
    System.ServiceModel.Activation.Configuration.SecurityIdentifierElement
    System.ServiceModel.Activities.Configuration.ChannelSettingsElement
    System.ServiceModel.Activities.Configuration.FactorySettingsElement
    System.ServiceModel.Activities.Tracking.Configuration.TrackingConfigurationElement
    System.ServiceModel.Configuration.AllowedAudienceUriElement
    System.ServiceModel.Configuration.AuthorizationPolicyTypeElement
    System.ServiceModel.Configuration.BaseAddressElement
    System.ServiceModel.Configuration.BaseAddressPrefixFilterElement
    System.ServiceModel.Configuration.BindingCollectionElement
    System.ServiceModel.Configuration.CertificateElement
    System.ServiceModel.Configuration.CertificateReferenceElement
    System.ServiceModel.Configuration.ChannelEndpointElement
    System.ServiceModel.Configuration.ClaimTypeElement
    System.ServiceModel.Configuration.ComContractElement
    System.ServiceModel.Configuration.ComMethodElement
    System.ServiceModel.Configuration.ComPersistableTypeElement
    System.ServiceModel.Configuration.ComUdtElement
    System.ServiceModel.Configuration.DefaultPortElement
    System.ServiceModel.Configuration.DelegatingHandlerElement
    System.ServiceModel.Configuration.DnsElement
    System.ServiceModel.Configuration.EndpointCollectionElement
    System.ServiceModel.Configuration.EndToEndTracingElement
    System.ServiceModel.Configuration.ExtensionElement
    System.ServiceModel.Configuration.HostElement
    System.ServiceModel.Configuration.HostTimeoutsElement
    System.ServiceModel.Configuration.HttpDigestClientElement
    System.ServiceModel.Configuration.HttpMessageHandlerFactoryElement
    System.ServiceModel.Configuration.IdentityElement
    System.ServiceModel.Configuration.IssuedTokenClientBehaviorsElement
    System.ServiceModel.Configuration.IssuedTokenClientElement
    System.ServiceModel.Configuration.IssuedTokenServiceElement
    System.ServiceModel.Configuration.MessageLoggingElement
    System.ServiceModel.Configuration.MetadataElement
    System.ServiceModel.Configuration.PeerCredentialElement
    System.ServiceModel.Configuration.PolicyImporterElement
    System.ServiceModel.Configuration.ProtocolMappingElement
    System.ServiceModel.Configuration.RsaElement
    System.ServiceModel.Configuration.SecureConversationServiceElement
    System.ServiceModel.Configuration.ServiceActivationElement
    System.ServiceModel.Configuration.ServiceElement
    System.ServiceModel.Configuration.ServiceEndpointElement
    System.ServiceModel.Configuration.ServiceModelConfigurationElement
    System.ServiceModel.Configuration.ServiceModelExtensionCollectionElement<TServiceModelExtensionElement>
    System.ServiceModel.Configuration.ServicePrincipalNameElement
    System.ServiceModel.Configuration.StandardEndpointElement
    System.ServiceModel.Configuration.TransportConfigurationTypeElement
    System.ServiceModel.Configuration.UserNameServiceElement
    System.ServiceModel.Configuration.UserPrincipalNameElement
    System.ServiceModel.Configuration.WindowsClientElement
    System.ServiceModel.Configuration.WindowsServiceElement
    System.ServiceModel.Configuration.WsdlImporterElement
    System.ServiceModel.Configuration.X509CertificateTrustedIssuerElement
    System.ServiceModel.Configuration.X509ClientCertificateAuthenticationElement
    System.ServiceModel.Configuration.X509ClientCertificateCredentialsElement
    System.ServiceModel.Configuration.X509DefaultServiceCertificateElement
    System.ServiceModel.Configuration.X509InitiatorCertificateClientElement
    System.ServiceModel.Configuration.X509InitiatorCertificateServiceElement
    System.ServiceModel.Configuration.X509PeerCertificateAuthenticationElement
    System.ServiceModel.Configuration.X509PeerCertificateElement
    System.ServiceModel.Configuration.X509RecipientCertificateClientElement
    System.ServiceModel.Configuration.X509RecipientCertificateServiceElement
    System.ServiceModel.Configuration.X509ScopedServiceCertificateElement
    System.ServiceModel.Configuration.X509ServiceCertificateAuthenticationElement
    System.ServiceModel.Configuration.XmlElementElement
    System.ServiceModel.Configuration.XPathMessageFilterElement
    System.ServiceModel.Discovery.Configuration.ContractTypeNameElement
    System.ServiceModel.Discovery.Configuration.DiscoveryClientSettingsElement
    System.ServiceModel.Discovery.Configuration.FindCriteriaElement
    System.ServiceModel.Discovery.Configuration.ScopeElement
    System.ServiceModel.Discovery.Configuration.UdpTransportSettingsElement
    System.ServiceModel.Routing.Configuration.BackupEndpointElement
    System.ServiceModel.Routing.Configuration.FilterElement
    System.ServiceModel.Routing.Configuration.FilterTableEntryElement
    System.ServiceModel.Routing.Configuration.NamespaceElement
    System.Web.Configuration.AssemblyInfo
    System.Web.Configuration.AuthorizationRule
    System.Web.Configuration.BufferModeSettings
    System.Web.Configuration.BuildProvider
    System.Web.Configuration.ClientTarget
    System.Web.Configuration.CodeSubDirectory
    System.Web.Configuration.Compiler
    System.Web.Configuration.Converter
    System.Web.Configuration.CustomError
    System.Web.Configuration.EventMappingSettings
    System.Web.Configuration.ExpressionBuilder
    System.Web.Configuration.FolderLevelBuildProvider
    System.Web.Configuration.FormsAuthenticationConfiguration
    System.Web.Configuration.FormsAuthenticationCredentials
    System.Web.Configuration.FormsAuthenticationUser
    System.Web.Configuration.FullTrustAssembly
    System.Web.Configuration.HttpHandlerAction
    System.Web.Configuration.HttpModuleAction
    System.Web.Configuration.IgnoreDeviceFilterElement
    System.Web.Configuration.NamespaceInfo
    System.Web.Configuration.OutputCacheProfile
    System.Web.Configuration.PartialTrustVisibleAssembly
    System.Web.Configuration.PassportAuthentication
    System.Web.Configuration.ProfileGroupSettings
    System.Web.Configuration.ProfilePropertySettings
    System.Web.Configuration.ProfileSettings
    System.Web.Configuration.ProtocolElement
    System.Web.Configuration.RuleSettings
    System.Web.Configuration.SqlCacheDependencyDatabase
    System.Web.Configuration.TagMapInfo
    System.Web.Configuration.TagPrefixInfo
    System.Web.Configuration.TransformerInfo
    System.Web.Configuration.TrustLevel
    System.Web.Configuration.UrlMapping
    System.Web.Configuration.WebPartsPersonalization
    System.Web.Configuration.WebPartsPersonalizationAuthorization
    System.Web.Mobile.DeviceFilterElement
    System.Web.Services.Configuration.DiagnosticsElement
    System.Web.Services.Configuration.ProtocolElement
    System.Web.Services.Configuration.SoapEnvelopeProcessingElement
    System.Web.Services.Configuration.SoapExtensionTypeElement
    System.Web.Services.Configuration.TypeElement
    System.Web.Services.Configuration.WsdlHelpGeneratorElement
    System.Web.Services.Configuration.WsiProfilesElement
    System.Web.UI.MobileControls.ControlElement
    System.Web.UI.MobileControls.DeviceElement
    System.Workflow.Runtime.Configuration.WorkflowRuntimeServiceElement
    System.Xaml.Hosting.Configuration.HandlerElement
    System.Xml.Serialization.Configuration.SchemaImporterExtensionElement
Il documento è risultato utile?
(1500 caratteri rimanenti)

Aggiunte alla community

AGGIUNGI
Microsoft sta conducendo un sondaggio in linea per comprendere l'opinione degli utenti in merito al sito Web di MSDN. Se si sceglie di partecipare, quando si lascia il sito Web di MSDN verrà visualizzato il sondaggio in linea.

Si desidera partecipare?
© 2013 Microsoft. Tutti i diritti riservati.