Este artículo se tradujo de forma manual. Mueva el puntero sobre las frases del artículo para ver el texto original.
Traducción
Original
Personas que lo han encontrado útil: 0 de 3 - Valorar este tema

ArrayList.Item (Propiedad)

Obtiene o establece el elemento que se encuentra en el índice especificado.

Espacio de nombres:  System.Collections
Ensamblado:  mscorlib (en mscorlib.dll)
public virtual Object this[
	int index
] { get; set; }

Parámetros

index
Tipo: System.Int32
Índice de base cero del elemento que se va a obtener o establecer.

Valor de propiedad

Tipo: System.Object
Elemento situado en el índice especificado.

Implementaciones

IList.Item[Int32]
Excepción Condición
ArgumentOutOfRangeException

El valor del parámetro index es menor que cero.

O bien

index es mayor o igual que Count.

El objeto ArrayList acepta null como valor válido y permite elementos duplicados.

Esta propiedad permite obtener acceso a un elemento específico de la colección utilizando la sintaxis siguiente: myCollection[index].

El lenguaje C# utiliza la palabra clave this para definir los indizadores en lugar de implementar la propiedad Item. Visual Basic implementa Item como propiedad predeterminada, lo que proporciona la misma funcionalidad de indización.

La recuperación del valor de esta propiedad es una operación O(1); el establecimiento de la propiedad también es una operación O(1).

En el código de ejemplo siguiente se crea una matriz ArrayList y se agregan varios elementos. En el ejemplo se muestra cómo tener acceso a elementos con la propiedad Item (el indizador en C#) y cómo modificar un elemento asignando un valor nuevo a la propiedad Item para un índice especificado. En el ejemplo también se muestra que no se puede utilizar la propiedad Item para agregar u obtener acceso a elementos fuera del tamaño actual de la lista.


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
 */


El siguiente ejemplo utiliza explícitamente la propiedad Item para asignar valores a elementos de la lista. En el ejemplo se define una clase que hereda una ArrayList y agrega un método para cifrar los elementos de lista.


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>


.NET Framework

Compatible con: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Compatible con: 4, 3.5 SP1

Windows 7, Windows Vista SP1 o posterior, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (no se admite Server Core), Windows Server 2008 R2 (se admite Server Core con SP1 o posterior), Windows Server 2003 SP2

.NET Framework no admite todas las versiones de todas las plataformas. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.

Fecha

Historial

Motivo

Junio de 2010

Se ha agregado un ejemplo.

Comentarios de los clientes.

¿Le ha resultado útil?
(Caracteres restantes: 1500)
Contenido de la comunidad Agregar