NameObjectCollectionBase Clase
Definición
Importante
Parte de la información hace referencia a la versión preliminar del producto, que puede haberse modificado sustancialmente antes de lanzar la versión definitiva. Microsoft no otorga ninguna garantía, explícita o implícita, con respecto a la información proporcionada aquí.
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
- Herencia
-
NameObjectCollectionBase
- Derivado
- Atributos
- Implementaciones
Ejemplos
En el ejemplo de código siguiente se muestra cómo implementar y usar la NameObjectCollectionBase clase .
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):
Comentarios
La estructura subyacente de esta clase es una tabla hash.
Cada elemento es un par clave-valor.
La capacidad de es NameObjectCollectionBase el número de elementos que NameObjectCollectionBase puede contener. A medida que se agregan elementos a , NameObjectCollectionBasela capacidad aumenta automáticamente según sea necesario mediante la reasignación.
El proveedor de código hash dispensa códigos hash para las claves de la NameObjectCollectionBase instancia. El proveedor de código hash predeterminado es .CaseInsensitiveHashCodeProvider
El comparador determina si dos claves son iguales. El comparador predeterminado es CaseInsensitiveComparer.
En .NET Framework versión 1.0, esta clase usa comparaciones de cadenas que distinguen referencias culturales. Sin embargo, en .NET Framework versión 1.1 y posteriores, esta clase usa CultureInfo.InvariantCulture al comparar cadenas. Para obtener más información sobre cómo afecta la referencia cultural a las comparaciones y la ordenación, vea Realizar Culture-Insensitive operaciones de cadena.
null se permite como clave o como valor.
Caution
El BaseGet método no distingue entre null eso se devuelve porque no se encuentra la clave especificada y null se devuelve porque el valor asociado a la clave es null.
Constructores
| Nombre | Description |
|---|---|
| NameObjectCollectionBase() |
Inicializa una nueva instancia de la NameObjectCollectionBase clase que está vacía. |
| NameObjectCollectionBase(IEqualityComparer) |
Inicializa una nueva instancia de la NameObjectCollectionBase clase que está vacía, tiene la capacidad inicial predeterminada y usa el objeto especificado IEqualityComparer . |
| NameObjectCollectionBase(IHashCodeProvider, IComparer) |
Obsoletos.
Inicializa una nueva instancia de la NameObjectCollectionBase clase que está vacía, tiene la capacidad inicial predeterminada y usa el proveedor de código hash especificado y el comparador especificado. |
| NameObjectCollectionBase(Int32, IEqualityComparer) |
Inicializa una nueva instancia de la NameObjectCollectionBase clase que está vacía, tiene la capacidad inicial especificada y usa el objeto especificado IEqualityComparer . |
| NameObjectCollectionBase(Int32, IHashCodeProvider, IComparer) |
Obsoletos.
Inicializa una nueva instancia de la NameObjectCollectionBase clase que está vacía, tiene la capacidad inicial especificada y usa el proveedor de código hash especificado y el comparador especificado. |
| NameObjectCollectionBase(Int32) |
Inicializa una nueva instancia de la NameObjectCollectionBase clase que está vacía, tiene la capacidad inicial especificada y usa el proveedor de código hash predeterminado y el comparador predeterminado. |
| NameObjectCollectionBase(SerializationInfo, StreamingContext) |
Inicializa una nueva instancia de la NameObjectCollectionBase clase que es serializable y usa los valores especificados SerializationInfo y StreamingContext. |
Propiedades
| Nombre | Description |
|---|---|
| Count |
Obtiene el número de pares clave-valor contenidos en la NameObjectCollectionBase instancia. |
| IsReadOnly |
Obtiene o establece un valor que indica si la NameObjectCollectionBase instancia es de solo lectura. |
| Keys |
Obtiene una NameObjectCollectionBase.KeysCollection instancia que contiene todas las claves de la NameObjectCollectionBase instancia. |
Métodos
| Nombre | Description |
|---|---|
| BaseAdd(String, Object) |
Agrega una entrada con la clave y el valor especificados en la NameObjectCollectionBase instancia. |
| BaseClear() |
Quita todas las entradas de la NameObjectCollectionBase instancia. |
| BaseGet(Int32) |
Obtiene el valor de la entrada en el índice especificado de la NameObjectCollectionBase instancia. |
| BaseGet(String) |
Obtiene el valor de la primera entrada con la clave especificada de la NameObjectCollectionBase instancia. |
| BaseGetAllKeys() |
Devuelve una String matriz que contiene todas las claves de la NameObjectCollectionBase instancia. |
| BaseGetAllValues() |
Devuelve una Object matriz que contiene todos los valores de la NameObjectCollectionBase instancia. |
| BaseGetAllValues(Type) |
Devuelve una matriz del tipo especificado que contiene todos los valores de la NameObjectCollectionBase instancia. |
| BaseGetKey(Int32) |
Obtiene la clave de la entrada en el índice especificado de la NameObjectCollectionBase instancia. |
| BaseHasKeys() |
Obtiene un valor que indica si la NameObjectCollectionBase instancia contiene entradas cuyas claves no |
| BaseRemove(String) |
Quita las entradas con la clave especificada de la NameObjectCollectionBase instancia. |
| BaseRemoveAt(Int32) |
Quita la entrada en el índice especificado de la NameObjectCollectionBase instancia. |
| BaseSet(Int32, Object) |
Establece el valor de la entrada en el índice especificado de la NameObjectCollectionBase instancia. |
| BaseSet(String, Object) |
Establece el valor de la primera entrada con la clave especificada en la NameObjectCollectionBase instancia, si se encuentra; de lo contrario, agrega una entrada con la clave y el valor especificados en la NameObjectCollectionBase instancia. |
| Equals(Object) |
Determina si el objeto especificado es igual al objeto actual. (Heredado de Object) |
| GetEnumerator() |
Devuelve un enumerador que recorre en iteración .NameObjectCollectionBase |
| GetHashCode() |
Actúa como la función hash predeterminada. (Heredado de Object) |
| GetObjectData(SerializationInfo, StreamingContext) |
Implementa la ISerializable interfaz y devuelve los datos necesarios para serializar la NameObjectCollectionBase instancia. |
| GetType() |
Obtiene el Type de la instancia actual. (Heredado de Object) |
| MemberwiseClone() |
Crea una copia superficial del Objectactual. (Heredado de Object) |
| OnDeserialization(Object) |
Implementa la ISerializable interfaz y genera el evento de deserialización cuando se completa la deserialización. |
| ToString() |
Devuelve una cadena que representa el objeto actual. (Heredado de Object) |
Implementaciones de interfaz explícitas
| Nombre | Description |
|---|---|
| ICollection.CopyTo(Array, Int32) |
Copia todo en NameObjectCollectionBase una unidimensional Arraycompatible, empezando por el índice especificado de la matriz de destino. |
| ICollection.IsSynchronized |
Obtiene un valor que indica si el NameObjectCollectionBase acceso al objeto está sincronizado (seguro para subprocesos). |
| ICollection.SyncRoot |
Obtiene un objeto que se puede usar para sincronizar el acceso al NameObjectCollectionBase objeto . |
Métodos de extensión
| Nombre | Description |
|---|---|
| AsParallel(IEnumerable) |
Habilita la paralelización de una consulta. |
| AsQueryable(IEnumerable) |
Convierte un IEnumerable en un IQueryable. |
| Cast<TResult>(IEnumerable) |
Convierte los elementos de un IEnumerable al tipo especificado. |
| OfType<TResult>(IEnumerable) |
Filtra los elementos de un IEnumerable en función de un tipo especificado. |
Se aplica a
Seguridad para subprocesos
Los miembros estáticos públicos (Shared en Visual Basic) de este tipo son seguros para subprocesos. No se garantiza que los miembros de instancia sean seguros para el acceso concurrente.
Esta implementación no proporciona un contenedor sincronizado (seguro para subprocesos) para una NameObjectCollectionBaseclase , pero las clases derivadas pueden crear sus propias versiones sincronizadas de NameObjectCollectionBase mediante la SyncRoot propiedad .
La enumeración a través de una colección no es intrínsecamente un procedimiento seguro para subprocesos. Incluso cuando se sincroniza una colección, otros subprocesos todavía pueden modificar la colección, lo que hace que el enumerador inicie una excepción. Para garantizar la seguridad de los subprocesos durante la enumeración, puede bloquear la colección durante toda la enumeración o detectar las excepciones resultantes de los cambios realizados por otros subprocesos.