Last active
August 13, 2017 15:15
-
-
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>.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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