System.Collections.Specialized.NameObjectCollectionBase
En savoir plus... Espace de noms : System.Collections.Specialized
Assembly : System (dans System.dll)
<SerializableAttribute> _ Public MustInherit Class NameObjectCollectionBase _ Implements ICollection, IEnumerable, ISerializable, IDeserializationCallback
[SerializableAttribute] public abstract class NameObjectCollectionBase : ICollection, IEnumerable, ISerializable, IDeserializationCallback
[SerializableAttribute] public ref class NameObjectCollectionBase abstract : ICollection, IEnumerable, ISerializable, IDeserializationCallback
[<AbstractClass>] [<SerializableAttribute>] type NameObjectCollectionBase = class interface ICollection interface IEnumerable interface ISerializable interface IDeserializationCallback end
Le type NameObjectCollectionBase expose les membres suivants.
| Nom | Description | |
|---|---|---|
|
NameObjectCollectionBase() | Initialise une nouvelle instance de la classe NameObjectCollectionBase qui est vide. |
|
NameObjectCollectionBase(IEqualityComparer) | Initialise une nouvelle instance de la classe NameObjectCollectionBase qui est vide, possède la capacité initiale par défaut et utilise l'objet IEqualityComparer spécifié. |
|
NameObjectCollectionBase(Int32) | Initialise une nouvelle instance de la classe NameObjectCollectionBase qui est vide, possède la capacité initiale spécifiée et utilise le fournisseur de code de hachage et le comparateur par défaut. |
|
NameObjectCollectionBase(IHashCodeProvider, IComparer) | Obsolète. Initialise une nouvelle instance de la classe NameObjectCollectionBase qui est vide, possède la capacité initiale par défaut et utilise le fournisseur de code de hachage spécifié, ainsi que le comparateur spécifié. |
|
NameObjectCollectionBase(Int32, IEqualityComparer) | Initialise une nouvelle instance de la classe NameObjectCollectionBase qui est vide, possède la capacité initiale spécifiée et utilise l'objet IEqualityComparer spécifié. |
|
NameObjectCollectionBase(SerializationInfo, StreamingContext) | Initialise une nouvelle instance de la classe NameObjectCollectionBase qui est sérialisable et utilise les System.Runtime.Serialization.SerializationInfo et System.Runtime.Serialization.StreamingContext spécifiés. |
|
NameObjectCollectionBase(Int32, IHashCodeProvider, IComparer) | Obsolète. Initialise une nouvelle instance de la classe NameObjectCollectionBase qui est vide, possède la capacité initiale spécifiée et utilise le fournisseur de code de hachage spécifié, ainsi que le comparateur spécifié. |
| Nom | Description | |
|---|---|---|
|
Count | Obtient le nombre de paires clé/valeur contenues dans l'instance de NameObjectCollectionBase. |
|
IsReadOnly | Obtient ou définit une valeur indiquant si l'instance de NameObjectCollectionBase est en lecture seule. |
|
Keys | Obtient une instance du NameObjectCollectionBase.KeysCollection qui contient toutes les clés dans l'instance de NameObjectCollectionBase. |
| Nom | Description | |
|---|---|---|
|
BaseAdd | Ajoute une entrée contenant la clé et la valeur spécifiées dans l'instance de NameObjectCollectionBase. |
|
BaseClear | Supprime toutes les entrées de l'instance de NameObjectCollectionBase. |
|
BaseGet(Int32) | Obtient la valeur de l'entrée à l'index spécifié de l'instance de NameObjectCollectionBase. |
|
BaseGet(String) | Obtient la valeur de la première entrée contenant la clé spécifiée dans l'instance de NameObjectCollectionBase. |
|
BaseGetAllKeys | Retourne un tableau String qui contient toutes les clés dans l'instance de NameObjectCollectionBase. |
|
BaseGetAllValues() | Retourne un tableau Object qui contient toutes les valeurs dans l'instance de NameObjectCollectionBase. |
|
BaseGetAllValues(Type) | Retourne un tableau du type spécifié qui contient toutes les valeurs dans l'instance de NameObjectCollectionBase. |
|
BaseGetKey | Obtient la clé de l'entrée à l'index spécifié de l'instance de NameObjectCollectionBase. |
|
BaseHasKeys | Obtient une valeur indiquant si l'instance du NameObjectCollectionBase contient des entrées dont les clés ne sont pas null. |
|
BaseRemove | Supprime les entrées contenant la clé spécifiée dans l'instance de NameObjectCollectionBase. |
|
BaseRemoveAt | Supprime les entrées à l'index spécifié de l'instance de NameObjectCollectionBase. |
|
BaseSet(Int32, Object) | Définit la valeur de l'entrée à l'index spécifié de l'instance de NameObjectCollectionBase. |
|
BaseSet(String, Object) | Définit la valeur de la première entrée contenant la clé spécifiée dans l'instance de NameObjectCollectionBase, le cas échéant ; sinon, ajoute une entrée contenant la clé et la valeur spécifiées dans l'instance de NameObjectCollectionBase. |
|
Equals(Object) | Détermine si l'Object spécifié est égal à l'Object en cours. (Hérité de Object.) |
|
Finalize | Autorise un objet à tenter de libérer des ressources et d'exécuter d'autres opérations de netto***ge avant qu'il ne soit récupéré par l'opération garbage collection. (Hérité de Object.) |
|
GetEnumerator | Retourne un énumérateur qui itère au sein de NameObjectCollectionBase. |
|
GetHashCode | Sert de fonction de hachage pour un type particulier. (Hérité de Object.) |
|
GetObjectData | Implémente l'interface ISerializable et retourne les données requises pour sérialiser l'instance de NameObjectCollectionBase. |
|
GetType | Obtient le Type de l'instance actuelle. (Hérité de Object.) |
|
MemberwiseClone | Crée une copie superficielle de l'objet Object actif. (Hérité de Object.) |
|
OnDeserialization | Implémente l'interface ISerializable et déclenche l'événement de désérialisation une fois que la désérialisation est terminée. |
|
ToString | Retourne une chaîne qui représente l'objet actuel. (Hérité de Object.) |
| Nom | Description | |
|---|---|---|
|
AsParallel | Active la parallélisation d'une requête. (Défini par ParallelEnumerable.) |
|
AsQueryable | Convertit un IEnumerable en IQueryable. (Défini par Queryable.) |
|
Cast<TResult> | Convertit les éléments d'un IEnumerable vers le type spécifié. (Défini par Enumerable.) |
|
OfType<TResult> | Filtre les éléments d'un IEnumerable en fonction du type spécifié. (Défini par Enumerable.) |
| Nom | Description | |
|---|---|---|
|
ICollection.CopyTo | Copie l'ensemble du NameObjectCollectionBase vers un Array unidimensionnel compatible, en commençant à l'index spécifié du tableau cible. |
|
ICollection.IsSynchronized | Obtient une valeur indiquant si l'accès à l'objet NameObjectCollectionBase est synchronisé (thread-safe). |
|
ICollection.SyncRoot | Obtient un objet qui peut être utilisé pour synchroniser l'accès à NameObjectCollectionBase. |
La structure sous-jacente pour cette classe est une table de hachage.
Chaque élément est une paire clé/valeur.
La capacité de NameObjectCollectionBase correspond au nombre d'éléments que peut contenir NameObjectCollectionBase. Lorsque des éléments sont ajoutés à NameObjectCollectionBase, la capacité augmente automatiquement par réallocation.
Le fournisseur de code de hachage fournit des codes de hachage pour les clés dans l'instance de NameObjectCollectionBase. Le fournisseur de code de hachage par défaut est CaseInsensitiveHashCodeProvider.
Le comparateur détermine si deux clés sont égales. Le comparateur par défaut est CaseInsensitiveComparer.
Dans la version 1.0 du .NET Framework, cette classe utilise des comparaisons de chaînes dépendantes de la culture. Toutefois, dans la version 1.1 et les versions ultérieures du .NET Framework, elle utilise CultureInfo.InvariantCulture pour les comparaisons de chaînes. Pour plus d'informations sur l'impact de la culture sur les comparaisons et le tri, consultez Comparaison et tri des données pour une culture spécifiqueComparaison et tri des données pour une culture spécifiqueet Exécution d'opérations de chaînes indépendantes de la culture.
null est autorisée comme clé ou comme valeur.
Attention
|
|---|
|
La méthode BaseGet ne distingue pas null qui est retourné parce que la clé spécifiée est introuvable et null, retourné parce que la valeur associée à la clé est null. |
L'exemple de code suivant montre comment implémenter et utiliser la classe NameObjectCollectionBase.
Imports System Imports System.Collections Imports System.Collections.Specialized Public Class MyCollection Inherits NameObjectCollectionBase ' Creates an empty collection. Public Sub New() End Sub 'New ' Adds elements from an IDictionary into the new collection. Public Sub New(d As IDictionary, bReadOnly As Boolean) Dim de As DictionaryEntry For Each de In d Me.BaseAdd(CType(de.Key, String), de.Value) Next de Me.IsReadOnly = bReadOnly End Sub 'New ' Gets a key-and-value pair (DictionaryEntry) using an index. Default Public ReadOnly Property Item(index As Integer) As DictionaryEntry Get return new DictionaryEntry( _ me.BaseGetKey(index), me.BaseGet(index) ) End Get End Property ' Gets or sets the value associated with the specified key. Default Public Property Item(key As String) As Object Get Return Me.BaseGet(key) End Get Set Me.BaseSet(key, value) End Set End Property ' Gets a String array that contains all the keys in the collection. Public ReadOnly Property AllKeys() As String() Get Return Me.BaseGetAllKeys() End Get End Property ' Gets an Object array that contains all the values in the collection. Public ReadOnly Property AllValues() As Array Get Return Me.BaseGetAllValues() End Get End Property ' Gets a String array that contains all the values in the collection. Public ReadOnly Property AllStringValues() As String() Get Return CType(Me.BaseGetAllValues(GetType(String)), String()) End Get End Property ' Gets a value indicating if the collection contains keys that are not null. Public ReadOnly Property HasKeys() As Boolean Get Return Me.BaseHasKeys() End Get End Property ' Adds an entry to the collection. Public Sub Add(key As String, value As Object) Me.BaseAdd(key, value) End Sub 'Add ' Removes an entry with the specified key from the collection. Overloads Public Sub Remove(key As String) Me.BaseRemove(key) End Sub 'Remove ' Removes an entry in the specified index from the collection. Overloads Public Sub Remove(index As Integer) Me.BaseRemoveAt(index) End Sub 'Remove ' Clears all the elements in the collection. Public Sub Clear() Me.BaseClear() End Sub 'Clear End Class 'MyCollection Public Class SamplesNameObjectCollectionBase Public Shared Sub Main() ' Creates and initializes a new MyCollection that is read-only. Dim d As New ListDictionary() d.Add("red", "apple") d.Add("yellow", "banana") d.Add("green", "pear") Dim myROCol As New MyCollection(d, True) ' Tries to add a new item. Try myROCol.Add("blue", "sky") Catch e As NotSupportedException Console.WriteLine(e.ToString()) End Try ' Displays the keys and values of the MyCollection. Console.WriteLine("Read-Only Collection:") PrintKeysAndValues(myROCol) ' Creates and initializes an empty MyCollection that is writable. Dim myRWCol As New MyCollection() ' Adds new items to the collection. myRWCol.Add("purple", "grape") myRWCol.Add("orange", "tangerine") myRWCol.Add("black", "berries") Console.WriteLine("Writable Collection (after adding values):") PrintKeysAndValues(myRWCol) ' Changes the value of one element. myRWCol("orange") = "grapefruit" Console.WriteLine("Writable Collection (after changing one value):") PrintKeysAndValues(myRWCol) ' Removes one item from the collection. myRWCol.Remove("black") Console.WriteLine("Writable Collection (after removing one value):") PrintKeysAndValues(myRWCol) ' Removes all elements from the collection. myRWCol.Clear() Console.WriteLine("Writable Collection (after clearing the collection):") PrintKeysAndValues(myRWCol) End Sub 'Main ' Prints the indexes, keys, and values. Public Shared Sub PrintKeysAndValues(myCol As MyCollection) Dim i As Integer For i = 0 To myCol.Count - 1 Console.WriteLine("[{0}] : {1}, {2}", i, myCol(i).Key, myCol(i).Value) Next i End Sub 'PrintKeysAndValues ' Prints the keys and values using AllKeys. Public Shared Sub PrintKeysAndValues2(myCol As MyCollection) Dim s As String For Each s In myCol.AllKeys Console.WriteLine("{0}, {1}", s, myCol(s)) Next s End Sub 'PrintKeysAndValues2 End Class 'SamplesNameObjectCollectionBase 'This code produces the following output. ' 'System.NotSupportedException: Collection is read-only. ' at System.Collections.Specialized.NameObjectCollectionBase.BaseAdd(String name, Object value) ' at SamplesNameObjectCollectionBase.Main() 'Read-Only Collection: '[0] : red, apple '[1] : yellow, banana '[2] : green, pear 'Writable Collection (after adding values): '[0] : purple, grape '[1] : orange, tangerine '[2] : black, berries 'Writable Collection (after changing one value): '[0] : purple, grape '[1] : orange, grapefruit '[2] : black, berries 'Writable Collection (after removing one value): '[0] : purple, grape '[1] : orange, grapefruit 'Writable Collection (after clearing the collection):
using System; using System.Collections; using System.Collections.Specialized; public class MyCollection : NameObjectCollectionBase { // Creates an empty collection. public MyCollection() { } // Adds elements from an IDictionary into the new collection. public MyCollection( IDictionary d, Boolean bReadOnly ) { foreach ( DictionaryEntry de in d ) { this.BaseAdd( (String) de.Key, de.Value ); } this.IsReadOnly = bReadOnly; } // Gets a key-and-value pair (DictionaryEntry) using an index. public DictionaryEntry this[ int index ] { get { return ( new DictionaryEntry( this.BaseGetKey(index), this.BaseGet(index) ) ); } } // Gets or sets the value associated with the specified key. public Object this[ String key ] { get { return( this.BaseGet( key ) ); } set { this.BaseSet( key, value ); } } // Gets a String array that contains all the keys in the collection. public String[] AllKeys { get { return( this.BaseGetAllKeys() ); } } // Gets an Object array that contains all the values in the collection. public Array AllValues { get { return( this.BaseGetAllValues() ); } } // Gets a String array that contains all the values in the collection. public String[] AllStringValues { get { return( (String[]) this.BaseGetAllValues( typeof( string ) )); } } // Gets a value indicating if the collection contains keys that are not null. public Boolean HasKeys { get { return( this.BaseHasKeys() ); } } // Adds an entry to the collection. public void Add( String key, Object value ) { this.BaseAdd( key, value ); } // Removes an entry with the specified key from the collection. public void Remove( String key ) { this.BaseRemove( key ); } // Removes an entry in the specified index from the collection. public void Remove( int index ) { this.BaseRemoveAt( index ); } // Clears all the elements in the collection. public void Clear() { this.BaseClear(); } } public class SamplesNameObjectCollectionBase { public static void Main() { // Creates and initializes a new MyCollection that is read-only. IDictionary d = new ListDictionary(); d.Add( "red", "apple" ); d.Add( "yellow", "banana" ); d.Add( "green", "pear" ); MyCollection myROCol = new MyCollection( d, true ); // Tries to add a new item. try { myROCol.Add( "blue", "sky" ); } catch ( NotSupportedException e ) { Console.WriteLine( e.ToString() ); } // Displays the keys and values of the MyCollection. Console.WriteLine( "Read-Only Collection:" ); PrintKeysAndValues( myROCol ); // Creates and initializes an empty MyCollection that is writable. MyCollection myRWCol = new MyCollection(); // Adds new items to the collection. myRWCol.Add( "purple", "grape" ); myRWCol.Add( "orange", "tangerine" ); myRWCol.Add( "black", "berries" ); Console.WriteLine( "Writable Collection (after adding values):" ); PrintKeysAndValues( myRWCol ); // Changes the value of one element. myRWCol["orange"] = "grapefruit"; Console.WriteLine( "Writable Collection (after changing one value):" ); PrintKeysAndValues( myRWCol ); // Removes one item from the collection. myRWCol.Remove( "black" ); Console.WriteLine( "Writable Collection (after removing one value):" ); PrintKeysAndValues( myRWCol ); // Removes all elements from the collection. myRWCol.Clear(); Console.WriteLine( "Writable Collection (after clearing the collection):" ); PrintKeysAndValues( myRWCol ); } // Prints the indexes, keys, and values. public static void PrintKeysAndValues( MyCollection myCol ) { for ( int i = 0; i < myCol.Count; i++ ) { Console.WriteLine( "[{0}] : {1}, {2}", i, myCol[i].Key, myCol[i].Value ); } } // Prints the keys and values using AllKeys. public static void PrintKeysAndValues2( MyCollection myCol ) { foreach ( String s in myCol.AllKeys ) { Console.WriteLine( "{0}, {1}", s, myCol[s] ); } } } /* This code produces the following output. System.NotSupportedException: Collection is read-only. at System.Collections.Specialized.NameObjectCollectionBase.BaseAdd(String name, Object value) at SamplesNameObjectCollectionBase.Main() Read-Only Collection: [0] : red, apple [1] : yellow, banana [2] : green, pear Writable Collection (after adding values): [0] : purple, grape [1] : orange, tangerine [2] : black, berries Writable Collection (after changing one value): [0] : purple, grape [1] : orange, grapefruit [2] : black, berries Writable Collection (after removing one value): [0] : purple, grape [1] : orange, grapefruit Writable Collection (after clearing the collection): */
#using <System.dll> using namespace System; using namespace System::Collections; using namespace System::Collections::Specialized; public ref class MyCollection : public NameObjectCollectionBase { private: DictionaryEntry^ _de; // Creates an empty collection. public: MyCollection() { _de = gcnew DictionaryEntry(); } // Adds elements from an IDictionary into the new collection. MyCollection( IDictionary^ d, Boolean bReadOnly ) { _de = gcnew DictionaryEntry(); for each ( DictionaryEntry^ de in d ) { this->BaseAdd( (String^) de->Key, de->Value ); } this->IsReadOnly = bReadOnly; } // Gets a key-and-value pair (DictionaryEntry) using an index. property DictionaryEntry^ default[ int ] { DictionaryEntry^ get(int index) { _de->Key = this->BaseGetKey(index); _de->Value = this->BaseGet(index); return( _de ); } } // Gets or sets the value associated with the specified key. property Object^ default[ String^ ] { Object^ get(String^ key) { return( this->BaseGet( key ) ); } void set( String^ key, Object^ value ) { this->BaseSet( key, value ); } } // Gets a String array that contains all the keys in the collection. property array<String^>^ AllKeys { array<String^>^ get() { return( (array<String^>^)this->BaseGetAllKeys() ); } } // Gets an Object array that contains all the values in the collection. property Array^ AllValues { Array^ get() { return( this->BaseGetAllValues() ); } } // Gets a String array that contains all the values in the collection. property array<String^>^ AllStringValues { array<String^>^ get() { return( (array<String^>^) this->BaseGetAllValues( String ::typeid )); } } // Gets a value indicating if the collection contains keys that are not null. property Boolean HasKeys { Boolean get() { return( this->BaseHasKeys() ); } } // Adds an entry to the collection. void Add( String^ key, Object^ value ) { this->BaseAdd( key, value ); } // Removes an entry with the specified key from the collection. void Remove( String^ key ) { this->BaseRemove( key ); } // Removes an entry in the specified index from the collection. void Remove( int index ) { this->BaseRemoveAt( index ); } // Clears all the elements in the collection. void Clear() { this->BaseClear(); } }; public ref class SamplesNameObjectCollectionBase { public: static void Main() { // Creates and initializes a new MyCollection that is read-only. IDictionary^ d = gcnew ListDictionary(); d->Add( "red", "apple" ); d->Add( "yellow", "banana" ); d->Add( "green", "pear" ); MyCollection^ myROCol = gcnew MyCollection( d, true ); // Tries to add a new item. try { myROCol->Add( "blue", "sky" ); } catch ( NotSupportedException^ e ) { Console::WriteLine( e->ToString() ); } // Displays the keys and values of the MyCollection. Console::WriteLine( "Read-Only Collection:" ); PrintKeysAndValues( myROCol ); // Creates and initializes an empty MyCollection that is writable. MyCollection^ myRWCol = gcnew MyCollection(); // Adds new items to the collection. myRWCol->Add( "purple", "grape" ); myRWCol->Add( "orange", "tangerine" ); myRWCol->Add( "black", "berries" ); Console::WriteLine( "Writable Collection (after adding values):" ); PrintKeysAndValues( myRWCol ); // Changes the value of one element. myRWCol["orange"] = "grapefruit"; Console::WriteLine( "Writable Collection (after changing one value):" ); PrintKeysAndValues( myRWCol ); // Removes one item from the collection. myRWCol->Remove( "black" ); Console::WriteLine( "Writable Collection (after removing one value):" ); PrintKeysAndValues( myRWCol ); // Removes all elements from the collection. myRWCol->Clear(); Console::WriteLine( "Writable Collection (after clearing the collection):" ); PrintKeysAndValues( myRWCol ); } // Prints the indexes, keys, and values. static void PrintKeysAndValues( MyCollection^ myCol ) { for ( int i = 0; i < myCol->Count; i++ ) { Console::WriteLine( "[{0}] : {1}, {2}", i, myCol[i]->Key, myCol[i]->Value ); } } // Prints the keys and values using AllKeys. static void PrintKeysAndValues2( MyCollection^ myCol ) { for each ( String^ s in myCol->AllKeys ) { Console::WriteLine( "{0}, {1}", s, myCol[s] ); } } }; int main() { SamplesNameObjectCollectionBase::Main(); } /* This code produces the following output. System.NotSupportedException: Collection is read-only. at System.Collections.Specialized.NameObjectCollectionBase.BaseAdd(String name, Object value) at SamplesNameObjectCollectionBase.Main() Read-Only Collection: [0] : red, apple [1] : yellow, banana [2] : green, pear Writable Collection (after adding values): [0] : purple, grape [1] : orange, tangerine [2] : black, berries Writable Collection (after changing one value): [0] : purple, grape [1] : orange, grapefruit [2] : black, berries Writable Collection (after removing one value): [0] : purple, grape [1] : orange, grapefruit Writable Collection (after clearing the collection): */
.NET Framework
Pris en charge dans : 4, 3.5, 3.0, 2.0, 1.1, 1.0.NET Framework Client Profile
Pris en charge dans : 4, 3.5 SP1Windows 7, Windows Vista SP1 ou ultérieur, Windows XP SP3, Windows XP SP2 Édition x64, Windows Server 2008 (installation minimale non prise en charge), Windows Server 2008 R2 (installation minimale prise en charge avec SP1 ou version ultérieure), Windows Server 2003 SP2
Le .NET Framework ne prend pas en charge toutes les versions de chaque plateforme. Pour obtenir la liste des versions prises en charge, consultez Configuration requise du .NET Framework.
Les membres statiques publics (Shared en Visual Basic) de ce type sont thread-safe. Il n'est pas garanti que les membres d'instance soient thread-safe.
Cette implémentation ne fournit pas de wrapper synchronisé (thread-safe) pour NameObjectCollectionBase, mais des classes dérivées peuvent créer leurs propres versions synchronisées de NameObjectCollectionBase à l'aide de la propriété SyncRoot.
L'énumération d'une collection n'est intrinsèquement pas une procédure thread-safe. Même lorsqu'une collection est synchronisée, les autres threads peuvent toujours modifier la collection, ce qui entraîne la levée d'une exception par l'énumérateur. Pour garantir la sécurité des threads lors de l'énumération, vous pouvez verrouiller la collection pour toute la durée de l'énumération ou intercepter les exceptions résultant de modifications apportées par d'autres threads.
Référence
Autres ressources
System.Collections.Specialized.NameObjectCollectionBase
System.Collections.Specialized.NameValueCollection
System.Configuration.ConfigurationSectionCollection
System.Configuration.ConfigurationSectionGroupCollection
System.Configuration.PropertyInformationCollection
System.Management.ManagementNamedValueCollection
System.Web.Configuration.VirtualDirectoryMappingCollection
System.Web.HttpApplicationState
System.Web.HttpApplicationStateBase
System.Web.HttpCookieCollection
System.Web.HttpFileCollection
System.Web.HttpFileCollectionBase
System.Web.HttpModuleCollection
System.Web.SessionState.SessionStateItemCollection
Attention