Nivel 6 — Genéricos y delegados
Genéricos
Notas originales de SunDiaL · Ver fuente en inglés
Los genéricos son funciones o tipos (clases) a los que no les importa con qué trabajan. Permiten escribir código que funciona con cualquier tipo sin reescribirlo para cada uno.
Puedes reconocer un genérico por su sintaxis con corchetes angulares:
<T>.
Un uso habitual de los genéricos son las colecciones, como List<T> o Dictionary<TKey, TValue>.
Ejemplo: una pila
Aquí tienes una implementación muy básica de una pila.
public class Stack<T>
{
private class Node<T>
{
public T Data { get; set; }
public Node<T> Next { get; set; }
public Node(T data, Node next)
{
Data = data;
Next = next;
}
}
private Node<T> top;
public void Add(T data)
{
top = new Node(data, top);
}
public T Remove()
{
if (top == null)
throw new InvalidOperationException("Stack is empty");
T result = top.Data;
top = top.Next;
return result;
}
}
public void Main()
{
Stack<int> myStack = new Stack<int>();
myStack.Add(1);
myStack.Add(2);
myStack.Add(3);
myStack.Add(4);
int x = myStack.Remove(); //4
myStack.Add(5);
//myStack will be [1, 2, 3, 5]
}