Collection Classe
Definizione
Un oggetto Collection
di Visual Basic è un set ordinato di elementi a cui è possibile fare riferimento come singola unità.A Visual Basic Collection
is an ordered set of items that can be referred to as a unit.
public ref class Collection sealed : System::Collections::IList
public ref class Collection sealed : System::Collections::IList, System::Runtime::Serialization::IDeserializationCallback, System::Runtime::Serialization::ISerializable
public sealed class Collection : System.Collections.IList
[System.Serializable]
public sealed class Collection : System.Collections.IList, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
type Collection = class
interface ICollection
interface IEnumerable
interface IList
type Collection = class
interface ICollection
interface IList
[<System.Serializable>]
type Collection = class
interface ICollection
interface IList
interface ISerializable
interface IDeserializationCallback
Public NotInheritable Class Collection
Implements IList
Public NotInheritable Class Collection
Implements IDeserializationCallback, IList, ISerializable
- Ereditarietà
-
Collection
- Attributi
- Implementazioni
Esempio
Nell'esempio seguente vengono creati l' Collection
oggetto names
e una finestra di dialogo con cui un utente può aggiungere oggetti (nomi) alla raccolta.The following example creates the Collection
object names
and a dialog box with which a user can add objects (names) to the collection. Visualizza quindi i nomi nella raccolta e infine svuota la raccolta senza eliminare l' Collection
oggetto stesso.It then displays the names in the collection, and finally empties the collection without disposing of the Collection
object itself.
Per verificarne il funzionamento, scegliere il comando Aggiungi classe dal menu progetto e dichiarare una variabile pubblica chiamata instanceName
a livello di modulo di nameClass
(tipo Public instanceName
) per includere i nomi di ogni istanza.To see how this works, choose the Add Class command from the Project menu and declare a public variable called instanceName
at the module level of nameClass
(type Public instanceName
) to hold the names of each instance. Lasciare il nome predefinito come nameClass
.Leave the default name as nameClass
. Copiare e incollare il codice seguente nella sezione generale di un altro modulo, quindi avviarlo con l'istruzione classNamer
in un'altra procedura.Copy and paste the following code into the General section of another module, and then start it with the statement classNamer
in another procedure. Questo esempio funziona solo con le applicazioni host che supportano le classi.(This example works only with host applications that support classes.)
Public Class nameClass
Public instanceName As String
End Class
Sub classNamer()
' Create a Visual Basic Collection object.
Dim names As New Microsoft.VisualBasic.Collection()
Dim key As Integer
Dim msg As String
Dim name As String
Dim nameList As String = ""
' 1. Get names from the user to add to the collection.
Do
Dim inst As New nameClass()
key += 1
msg = "Please enter a name for this object." & vbCrLf &
"Press Cancel to see names in collection."
name = InputBox(msg, "Name the Collection items")
inst.instanceName = name
' If user entered a name, add it to the collection.
If inst.instanceName <> "" Then
names.Add(inst, CStr(key))
End If
Loop Until name = ""
' 2. Create and display a list of names from the collection.
For Each oneInst As nameClass In names
nameList &= oneInst.instanceName & vbCrLf
Next oneInst
MsgBox(nameList, , "Instance Names in names Collection")
' 3. Remove elements from the collection without disposing of the collection.
For count As Integer = 1 To names.Count
names.Remove(1)
' Since Visual Basic collections are reindexed automatically,
' remove the first member on each iteration.
Next count
End Sub
Commenti
Nota
Quando possibile, utilizzare le raccolte generiche negli spazi dei nomi System.Collections.Generic o System.Collections.Concurrent anziché una Collection
di Visual Basic.Whenever possible, you should use the generic collections in the System.Collections.Generic namespace or the System.Collections.Concurrent namespace instead of a Visual Basic Collection
. Per altre informazioni, vedere Collections-C# or collections-Visual Basic.For more information, see Collections - C# or Collections - Visual Basic.
L' Collection
oggetto Visual Basic fornisce un modo pratico per fare riferimento a un gruppo correlato di elementi come singolo oggetto.The Visual Basic Collection
object provides a convenient way to refer to a related group of items as a single object. Gli elementi, o elementi, in una raccolta devono essere correlati solo dal fatto che esistono nella raccolta.The items, or elements, in a collection need only be related by the fact that they exist in the collection. Gli elementi di una raccolta non devono condividere lo stesso tipo di dati.Elements of a collection do not have to share the same data type.
È possibile creare una raccolta nello stesso modo in cui si creano altri oggetti, come illustrato nell'esempio seguente.You can create a collection the same way you create other objects, as the following example illustrates.
Dim coll As New Microsoft.VisualBasic.Collection()
Dopo aver creato una raccolta, è possibile eseguire una delle operazioni seguenti:Once you have created a collection, you can do any of the following:
Aggiungere un elemento con il Add metodo.Add an element with the Add method.
Rimuovere un elemento con il Remove metodo.Remove an element with the Remove method.
Rimuovere tutti gli elementi con il Clear metodo.Remove all elements with the Clear method.
Individuare il numero di elementi contenuti nella raccolta con la Count Proprietà.Find out how many elements the collection contains with the Count property.
Controllare se un elemento specifico è presente con il Contains metodo.Check whether a specific element is present with the Contains method.
Restituisce un elemento specifico dalla raccolta con la Item[] Proprietà.Return a specific element from the collection with the Item[] property.
Scorre l'intera raccolta con la per ogni... Istruzione successiva.Iterate through the entire collection with the For Each...Next Statement.
Nota
Sebbene l'
Collection
oggetto Visual Basic disponga di funzionalità identiche all'Collection
oggetto in Visual Basic 6,0, le due non possono interagire in un ambiente com.Although the Visual BasicCollection
object has functionality identical to theCollection
object in Visual Basic 6.0, the two cannot interoperate in a COM environment.Attenzione
L'iterazione di un Visual Basic
Collection
non è una procedura thread-safe.Iterating through a Visual BasicCollection
is not a thread-safe procedure. Anche se la raccolta è sincronizzata, gli altri thread possono comunque modificare la raccolta, causando la generazione di un'eccezione da parte dell'enumeratore.Even if the collection is synchronized, other threads can still modify the collection, causing the enumerator to throw an exception. Per garantire thread safety durante l'enumerazione, bloccare la raccolta o intercettare le eccezioni derivanti dalle modifiche apportate da altri thread.To guarantee thread safety during enumeration, either lock the collection or catch the exceptions resulting from changes made by other threads. Per ulteriori informazioni sul blocco di un elemento di programmazione, vedere istruzione SyncLock.For more information on locking a programming element, see SyncLock Statement.
Costruttori
Collection() |
Crea e restituisce un nuovo oggetto Collection Visual Basic.Creates and returns a new Visual Basic Collection object. |
Proprietà
Count |
Ottiene il numero di elementi contenuti in una raccolta.Gets the number of elements in a collection. |
Item[Int32] |
Ottiene un elemento specifico di un oggetto |
Item[Object] |
Ottiene un elemento specifico di un oggetto |
Item[String] |
Ottiene un elemento specifico di un oggetto |
Metodi
Add(Object, String, Object, Object) |
Aggiunge un elemento all'oggetto |
Clear() |
Elimina tutti gli elementi di un oggetto |
Contains(String) |
Restituisce un valore che indica se un oggetto |
Equals(Object) |
Determina se l'oggetto specificato è uguale all'oggetto corrente.Determines whether the specified object is equal to the current object. (Ereditato da Object) |
GetEnumerator() |
Restituisce un enumeratore che consente di scorrere la raccolta.Returns an enumerator that iterates through the collection. |
GetHashCode() |
Funge da funzione hash predefinita.Serves as the default hash function. (Ereditato da Object) |
GetType() |
Ottiene l'oggetto Type dell'istanza corrente.Gets the Type of the current instance. (Ereditato da Object) |
MemberwiseClone() |
Crea una copia superficiale dell'oggetto Object corrente.Creates a shallow copy of the current Object. (Ereditato da Object) |
Remove(Int32) |
Rimuove un elemento dall'oggetto |
Remove(String) |
Rimuove un elemento dall'oggetto |
ToString() |
Restituisce una stringa che rappresenta l'oggetto corrente.Returns a string that represents the current object. (Ereditato da Object) |
Implementazioni dell'interfaccia esplicita
ICollection.CopyTo(Array, Int32) |
Copia gli elementi di Collection in Array a partire da un particolare indice Array.Copies the elements of the Collection to an Array, starting at a particular Array index. |
ICollection.Count |
Ottiene il numero di elementi in questa raccolta.Gets the number of items in this collection. |
ICollection.IsSynchronized |
Ottiene un valore che indica se l'accesso all'oggetto Collection è sincronizzato (thread-safe).Gets a value that indicates whether access to the Collection object is synchronized (thread-safe). |
ICollection.SyncRoot |
Ottiene un oggetto che può essere usato per sincronizzare l'accesso all'oggetto Collection.Gets an object that can be used to synchronize access to the Collection object. |
IDeserializationCallback.OnDeserialization(Object) |
Viene eseguito dopo che tutto l'oggetto grafico Collection è stato deserializzato.Runs after the entire Collection object graph has been deserialized. |
IEnumerable.GetEnumerator() |
Ottiene un enumeratore con cui è possibile scorrere la raccolta.Gets an enumerator that iterates through the collection. |
IList.Add(Object) |
Aggiunge un elemento alla raccolta.Adds an item to the collection. |
IList.Clear() |
Consente di rimuovere tutti gli elementi dall'oggetto Collection.Removes all items from the Collection object. |
IList.Contains(Object) |
Stabilisce se l'oggetto Collection contiene un valore specifico.Determines whether the Collection object contains a specific value. |
IList.IndexOf(Object) |
Consente di determinare l'indice di un elemento specifico dell'oggetto Collection.Determines the index of a specific item in the Collection object. |
IList.Insert(Int32, Object) |
Inserisce un elemento nell'oggetto Collection in corrispondenza dell'indice specificato.Inserts an item to the Collection object at the specified index. |
IList.IsFixedSize |
Ottiene un valore che indica se le dimensioni dell'oggetto Collection sono fisse.Gets a value that indicates whether the Collection object has a fixed size. |
IList.IsReadOnly |
Ottiene un valore che indica se l'oggetto Collection è di sola lettura.Gets a value that indicates whether the Collection object is. |
IList.Item[Int32] |
Ottiene o imposta l'elemento in corrispondenza dell'indice specificato.Gets or sets the element at the specified index. |
IList.Remove(Object) |
Consente di rimuovere la prima occorrenza di un oggetto specifico dall'oggetto Collection.Removes the first occurrence of a specific object from the Collection object. |
IList.RemoveAt(Int32) |
Rimuove l'oggetto Collection in corrispondenza dell'indice specificato.Removes the Collection object item at the specified index. |
ISerializable.GetObjectData(SerializationInfo, StreamingContext) |
Restituisce i dati necessari per la serializzazione dell'oggetto Collection.Returns the data needed to serialize the Collection object. |
Metodi di estensione
Cast<TResult>(IEnumerable) |
Esegue il cast degli elementi di un oggetto IEnumerable nel tipo specificato.Casts the elements of an IEnumerable to the specified type. |
OfType<TResult>(IEnumerable) |
Filtra gli elementi di un oggetto IEnumerable in base a un tipo specificato.Filters the elements of an IEnumerable based on a specified type. |
AsParallel(IEnumerable) |
Consente la parallelizzazione di una query.Enables parallelization of a query. |
AsQueryable(IEnumerable) |
Converte un oggetto IEnumerable in un oggetto IQueryable.Converts an IEnumerable to an IQueryable. |