Lire en anglais

Partager via


ArrayList.Item[Int32] Propriété

Définition

Obtient ou définit l'élément au niveau de l'index spécifié.

C#
public virtual object this[int index] { get; set; }
C#
public virtual object? this[int index] { get; set; }

Paramètres

index
Int32

Index de base zéro de l'élément à obtenir ou à définir.

Valeur de propriété

Élément au niveau de l'index spécifié.

Implémente

Exceptions

index est inférieur à zéro.

- ou -

index est supérieur ou égal à Count.

Exemples

L’exemple de code suivant crée un ArrayList et ajoute plusieurs éléments. L’exemple illustre l’accès aux éléments avec la Item[] propriété (l’indexeur en C#) et la modification d’un élément en affectant une nouvelle valeur à la Item[] propriété pour un index spécifié. L’exemple montre également que la Item[] propriété ne peut pas être utilisée pour accéder ou ajouter des éléments en dehors de la taille actuelle de la liste.

C#
using System;
using System.Collections;

public class Example
{
    public static void Main()
    {
        // Create an empty ArrayList, and add some elements.
        ArrayList stringList = new ArrayList();

        stringList.Add("a");
        stringList.Add("abc");
        stringList.Add("abcdef");
        stringList.Add("abcdefg");

        // The Item property is an indexer, so the property name is
        // not required.
        Console.WriteLine("Element {0} is \"{1}\"", 2, stringList[2]);

        // Assigning a value to the property changes the value of
        // the indexed element.
        stringList[2] = "abcd";
        Console.WriteLine("Element {0} is \"{1}\"", 2, stringList[2]);

        // Accessing an element outside the current element count
        // causes an exception.
        Console.WriteLine("Number of elements in the list: {0}",
            stringList.Count);
        try
        {
            Console.WriteLine("Element {0} is \"{1}\"",
                stringList.Count, stringList[stringList.Count]);
        }
        catch(ArgumentOutOfRangeException aoore)
        {
            Console.WriteLine("stringList({0}) is out of range.",
                stringList.Count);
        }

        // You cannot use the Item property to add new elements.
        try
        {
            stringList[stringList.Count] = "42";
        }
        catch(ArgumentOutOfRangeException aoore)
        {
            Console.WriteLine("stringList({0}) is out of range.",
                stringList.Count);
        }

        Console.WriteLine();
        for (int i = 0; i < stringList.Count; i++)
        {
            Console.WriteLine("Element {0} is \"{1}\"", i,
                stringList[i]);
        }

        Console.WriteLine();
        foreach (object o in stringList)
        {
            Console.WriteLine(o);
        }
    }
}
/*
 This code example produces the following output:

Element 2 is "abcdef"
Element 2 is "abcd"
Number of elements in the list: 4
stringList(4) is out of range.
stringList(4) is out of range.

Element 0 is "a"
Element 1 is "abc"
Element 2 is "abcd"
Element 3 is "abcdefg"

a
abc
abcd
abcdefg
 */

L’exemple suivant utilise explicitement la Item[] propriété pour affecter des valeurs aux éléments de la liste. L’exemple définit une classe qui hérite d’un ArrayList et ajoute une méthode pour brouiller les éléments de liste.

C#
using System;
using System.Collections;

public class ScrambleList : ArrayList
{
    public static void Main()
    {
        // Create an empty ArrayList, and add some elements.
        ScrambleList integerList = new ScrambleList();

        for (int i = 0; i < 10; i++)
        {
            integerList.Add(i);
        }

        Console.WriteLine("Ordered:\n");
        foreach (int value in integerList)
        {
            Console.Write("{0}, ", value);
        }
        Console.WriteLine("<end>\n\nScrambled:\n");

        // Scramble the order of the items in the list.
        integerList.Scramble();

        foreach (int value in integerList)
        {
            Console.Write("{0}, ", value);
        }
        Console.WriteLine("<end>\n");
    }

    public void Scramble()
    {
        int limit = this.Count;
        int temp;
        int swapindex;
        Random rnd = new Random();
        for (int i = 0; i < limit; i++)
        {
            // The Item property of ArrayList is the default indexer. Thus,
            // this[i] is used instead of Item[i].
            temp = (int)this[i];
            swapindex = rnd.Next(0, limit - 1);
            this[i] = this[swapindex];
            this[swapindex] = temp;
        }
    }
}

// The program produces output similar to the following:
//
// Ordered:
//
// 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, <end>
//
// Scrambled:
//
// 5, 2, 8, 9, 6, 1, 7, 0, 4, 3, <end>

Remarques

Retourne Item[] un Object, vous devrez peut-être convertir la valeur retournée en type d’origine afin de la manipuler. Il est important de noter que n’est ArrayList pas une collection fortement typée. Pour obtenir une alternative fortement typée, consultez List<T>.

ArrayList accepte null comme valeur valide et autorise les éléments en double.

Cette propriété permet d'accéder à un élément spécifique dans la collection à l'aide de la syntaxe suivante : myCollection[index].

Le langage C# utilise le mot clé this pour définir les indexeurs au lieu d'implémenter la propriété Item[]. Visual Basic implémente Item[] comme propriété par défaut, ce qui fournit les mêmes fonctionnalités d'indexation.

La récupération de la valeur de cette propriété est une O(1) opération ; la définition de la propriété est également une O(1) opération.

S’applique à

Produit Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1
UWP 10.0

Voir aussi