NameObjectCollectionBase Classe

Définition

Fournit la abstract classe de base pour une collection de clés et String de valeurs associées Object accessibles avec la clé ou avec l’index.

public ref class NameObjectCollectionBase abstract : System::Collections::ICollection
public ref class NameObjectCollectionBase abstract : System::Collections::ICollection, System::Runtime::Serialization::IDeserializationCallback, System::Runtime::Serialization::ISerializable
public abstract class NameObjectCollectionBase : System.Collections.ICollection
[System.Serializable]
public abstract class NameObjectCollectionBase : System.Collections.ICollection, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
public abstract class NameObjectCollectionBase : System.Collections.ICollection, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
type NameObjectCollectionBase = class
    interface ICollection
    interface IEnumerable
[<System.Serializable>]
type NameObjectCollectionBase = class
    interface ICollection
    interface IEnumerable
    interface ISerializable
    interface IDeserializationCallback
type NameObjectCollectionBase = class
    interface ICollection
    interface IEnumerable
    interface IDeserializationCallback
    interface ISerializable
Public MustInherit Class NameObjectCollectionBase
Implements ICollection
Public MustInherit Class NameObjectCollectionBase
Implements ICollection, IDeserializationCallback, ISerializable
Héritage
NameObjectCollectionBase
Dérivé
Attributs
Implémente

Exemples

L’exemple de code suivant montre comment implémenter et utiliser la NameObjectCollectionBase classe.

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

*/
Imports System.Collections
Imports System.Collections.Specialized

Public Class MyCollection
   Inherits NameObjectCollectionBase

   ' Creates an empty collection.
   Public Sub New()
   End Sub

   ' 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

   ' 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

   ' Removes an entry with the specified key from the collection.
   Overloads Public Sub Remove(key As String)
      Me.BaseRemove(key)
   End Sub

   ' Removes an entry in the specified index from the collection.
   Overloads Public Sub Remove(index As Integer)
      Me.BaseRemoveAt(index)
   End Sub

   ' Clears all the elements in the collection.
   Public Sub Clear()
      Me.BaseClear()
   End Sub

End Class


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

   ' 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

   ' 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

End Class


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

Remarques

La structure sous-jacente de cette classe est une table de hachage.

Chaque élément est une paire clé/valeur.

La capacité d’un NameObjectCollectionBase est le nombre d’éléments qu’il NameObjectCollectionBase peut contenir. À mesure que les éléments sont ajoutés à un NameObjectCollectionBase, la capacité est automatiquement augmentée en fonction des besoins grâce à la réaffectation.

Le fournisseur de code de hachage distribue des codes de hachage pour les clés dans l’instance NameObjectCollectionBase . Le fournisseur de code de hachage par défaut est le CaseInsensitiveHashCodeProvider.

Le comparateur détermine si deux clés sont égales. Le comparateur par défaut est le CaseInsensitiveComparer.

Dans .NET Framework version 1.0, cette classe utilise des comparaisons de chaînes sensibles à la culture. Toutefois, dans .NET Framework version 1.1 et ultérieure, cette classe utilise CultureInfo.InvariantCulture lors de la comparaison de chaînes. Pour plus d’informations sur la façon dont la culture affecte les comparaisons et le tri, consultez Exécution d’opérations de chaîne Culture-Insensitive.

null est autorisé en tant que clé ou en tant que valeur.

Avertissement

La BaseGet méthode ne fait pas la distinction entre null ce qui est retourné, car la clé spécifiée est introuvable et null elle est retournée, car la valeur associée à la clé est null.

Constructeurs

Nom Description
NameObjectCollectionBase()

Initialise une nouvelle instance de la NameObjectCollectionBase classe vide.

NameObjectCollectionBase(IEqualityComparer)

Initialise une nouvelle instance de la NameObjectCollectionBase classe vide, a la capacité initiale par défaut et utilise l’objet spécifié IEqualityComparer .

NameObjectCollectionBase(IHashCodeProvider, IComparer)
Obsolète.

Initialise une nouvelle instance de la NameObjectCollectionBase classe vide, a la capacité initiale par défaut et utilise le fournisseur de code de hachage spécifié et le comparateur spécifié.

NameObjectCollectionBase(Int32, IEqualityComparer)

Initialise une nouvelle instance de la NameObjectCollectionBase classe vide, a la capacité initiale spécifiée et utilise l’objet spécifié IEqualityComparer .

NameObjectCollectionBase(Int32, IHashCodeProvider, IComparer)
Obsolète.

Initialise une nouvelle instance de la NameObjectCollectionBase classe vide, a la capacité initiale spécifiée et utilise le fournisseur de code de hachage spécifié et le comparateur spécifié.

NameObjectCollectionBase(Int32)

Initialise une nouvelle instance de la NameObjectCollectionBase classe vide, a la capacité initiale spécifiée et utilise le fournisseur de code de hachage par défaut et le comparateur par défaut.

NameObjectCollectionBase(SerializationInfo, StreamingContext)

Initialise une nouvelle instance de la NameObjectCollectionBase classe sérialisable et utilise les éléments spécifiés SerializationInfo et StreamingContext.

Propriétés

Nom Description
Count

Obtient le nombre de paires clé/valeur contenues dans l’instance NameObjectCollectionBase .

IsReadOnly

Obtient ou définit une valeur indiquant si l’instance NameObjectCollectionBase est en lecture seule.

Keys

Obtient une NameObjectCollectionBase.KeysCollection instance qui contient toutes les clés de l’instance NameObjectCollectionBase .

Méthodes

Nom Description
BaseAdd(String, Object)

Ajoute une entrée avec la clé et la valeur spécifiées dans l’instance NameObjectCollectionBase .

BaseClear()

Supprime toutes les entrées de l’instance NameObjectCollectionBase .

BaseGet(Int32)

Obtient la valeur de l’entrée à l’index spécifié de l’instance NameObjectCollectionBase .

BaseGet(String)

Obtient la valeur de la première entrée avec la clé spécifiée de l’instance NameObjectCollectionBase .

BaseGetAllKeys()

Retourne un String tableau qui contient toutes les clés de l’instance NameObjectCollectionBase .

BaseGetAllValues()

Retourne un Object tableau qui contient toutes les valeurs de l’instance NameObjectCollectionBase .

BaseGetAllValues(Type)

Retourne un tableau du type spécifié qui contient toutes les valeurs de l’instance NameObjectCollectionBase .

BaseGetKey(Int32)

Obtient la clé de l’entrée à l’index spécifié de l’instance NameObjectCollectionBase .

BaseHasKeys()

Obtient une valeur indiquant si l’instance NameObjectCollectionBase contient des entrées dont les clés ne sont pas null.

BaseRemove(String)

Supprime les entrées avec la clé spécifiée de l’instance NameObjectCollectionBase .

BaseRemoveAt(Int32)

Supprime l’entrée à l’index spécifié de l’instance NameObjectCollectionBase .

BaseSet(Int32, Object)

Définit la valeur de l’entrée à l’index spécifié de l’instance NameObjectCollectionBase .

BaseSet(String, Object)

Définit la valeur de la première entrée avec la clé spécifiée dans l’instance NameObjectCollectionBase , si elle est trouvée ; sinon, ajoute une entrée avec la clé et la valeur spécifiées dans l’instance NameObjectCollectionBase .

Equals(Object)

Détermine si l’objet spécifié est égal à l’objet actuel.

(Hérité de Object)
GetEnumerator()

Retourne un énumérateur qui itère dans le NameObjectCollectionBase.

GetHashCode()

Sert de fonction de hachage par défaut.

(Hérité de Object)
GetObjectData(SerializationInfo, StreamingContext)

Implémente l’interface ISerializable et retourne les données nécessaires pour sérialiser l’instance NameObjectCollectionBase .

GetType()

Obtient la Type de l’instance actuelle.

(Hérité de Object)
MemberwiseClone()

Crée une copie superficielle du Objectactuel.

(Hérité de Object)
OnDeserialization(Object)

Implémente l’interface ISerializable et déclenche l’événement de désérialisation lorsque la désérialisation est terminée.

ToString()

Retourne une chaîne qui représente l’objet actuel.

(Hérité de Object)

Implémentations d’interfaces explicites

Nom Description
ICollection.CopyTo(Array, Int32)

Copie l’intégralité NameObjectCollectionBase dans une dimension unidimensionnelle Arraycompatible, 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 à l’objet NameObjectCollectionBase .

Méthodes d’extension

Nom Description
AsParallel(IEnumerable)

Active la parallélisation d’une requête.

AsQueryable(IEnumerable)

Convertit un IEnumerable en IQueryable.

Cast<TResult>(IEnumerable)

Convertit les éléments d’un IEnumerable en type spécifié.

OfType<TResult>(IEnumerable)

Filtre les éléments d’une IEnumerable en fonction d’un type spécifié.

S’applique à

Cohérence de thread

Les membres statiques publics (Shared en Visual Basic) de ce type sont thread-safe. Il n'y a aucune garantie que les membres d’instance soient thread-safe.

Cette implémentation ne fournit pas de wrapper synchronisé (thread safe) pour un NameObjectCollectionBase, mais les classes dérivées peuvent créer leurs propres versions synchronisées de la propriété à l’aide de la NameObjectCollectionBaseSyncRoot propriété.

L’énumération par le biais d’une collection n’est intrinsèquement pas une procédure sécurisée de thread. Même lorsqu’une collection est synchronisée, d’autres threads peuvent toujours modifier la collection, ce qui provoque la levée d’une exception par l’énumérateur. Pour garantir la sécurité des threads pendant l’énumération, vous pouvez verrouiller la collection pendant toute l’énumération ou intercepter les exceptions résultant des modifications apportées par d’autres threads.

Voir aussi