Skip to content

Instantly share code, notes, and snippets.

@Fhernd
Last active August 13, 2017 15:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fhernd/47e238868af9b09d1ae68394e172fd50 to your computer and use it in GitHub Desktop.
Save Fhernd/47e238868af9b09d1ae68394e172fd50 to your computer and use it in GitHub Desktop.
Creación de una colección personalizada con un tipo paramétrico. Implementa a la interfaz IEnumerable<T>.
using System;
using System.Collections.Generic;
namespace cap07.coleccionenteros
{
class Lista<T> : IEnumerable<T>
{
T[] elementos = null;
int indice = 0;
public Lista(int n)
{
elementos = new T[n];
}
public void AgregarElemento(T elemento)
{
elementos[indice] = elemento;
++indice;
}
// Implementación GetEnumerator genérico:
public IEnumerator<T> GetEnumerator()
{
foreach(T elemento in elementos)
{
if(elemento == null)
{
break;
}
yield return elemento;
}
}
// Implementación GetEnumerator no-genérico:
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
public class TestLista
{
public static void Main()
{
Lista<String> tresMaestros = new Lista<string>(3);
tresMaestros.AgregarElemento("Dostoevsky");
tresMaestros.AgregarElemento("Balzac");
tresMaestros.AgregarElemento("Dickens");
foreach(String maestro in tresMaestros)
{
Console.WriteLine(maestro);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment