using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace Generic_Tab
{
class GenericArray<T> : IEnumerable<T>
{
//------- Hashtable -------------------------------------------------
private Hashtable array; //Deklaracja tablicy typu Hashtable
private uint size;
public GenericArray(uint size)
{
array = new Hashtable(); //Utworzenie tablicy konstruktorem
this.size = size;
}
public T this[uint i]
{
get
{
return array.ContainsKey(i) ? (T)array[i] : default(T);
}
set
{
if (i >= size || i < 0)
throw new IndexOutOfRangeException();
if (!value.Equals(default(T)))
{
array[i] = value;
}
else if (array.Contains(i))
{
array.Remove(i);
}
}
}
public IEnumerator<T> GetEnumerator()
{
foreach (DictionaryEntry entry in array)
{
yield return (T)entry.Value ;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
foreach (DictionaryEntry entry in array)
{
yield return (T)entry.Value;
}
}
//-------- Dictionary ---------------------------------------------------
/*private Dictionary<uint, T> array;
private uint size;
public GenericArray(uint size)
{
array = new Dictionary<uint, T>(); //Utworzenie tablicy konstruktorem
this.size = size;
}
public T this[uint index]
{
get
{
return array.ContainsKey(index) ? (T)array[index] : default(T);
}
set
{
if (index >= size || index < 0)
throw new IndexOutOfRangeException();
if (!value.Equals(default(T)))
{
array[index] = value;
}
else if (array.ContainsKey(index))
{
array.Remove(index);
}
}
}
public IEnumerator<T> GetEnumerator()
{
foreach (KeyValuePair<uint, T> keyValuePair in array)
{
yield return keyValuePair.Value;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
foreach (KeyValuePair<uint, T> keyValuePair in array)
{
yield return keyValuePair.Value;
}
}*/
//----------------------------------------------------------------
}
class Test
{
//Przykład uzycia i obsługi tablicy generycznej
static void Main(string[] args)
{
uint size = 6;
//--------------------------------------------------
GenericArray<int> intArray = new GenericArray<int>(size);
for (uint c = 0; c < 4; c++) //Wstawienie wartości do tablicy
{
intArray[c] = (int)(c*c);
}
intArray[4] = 0;
intArray[5] = 7;
Console.Write("\nTablica int = [ "); //Pobranie wartości do wyświetlenia
foreach (int s in intArray)
{
Console.Write(s + " ");
}
Console.Write("]\n");
//--------------------------------------------------
GenericArray<char> charArray = new GenericArray<char>(size);
for (uint c = 0; c < size; c++) //Wstawienie charów do tablicy
{
charArray[c] = (char)(c + 97);
}
Console.Write("Tablica char = [ ");
foreach (char s in charArray)
{
Console.Write(s + " ");
}
Console.Write("]\n");
Console.ReadKey();
}
}
}