1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
|
using System;
using System.Collections.Generic;
namespace TestIndexer
{
class Program
{
static void Main(string[] args)
{
MyList<Single> MyTest = new MyList<Single>();
MyTest["Toto"] = new List<Single> { 0.25f, 0.66f };
MyTest["Titi"] = new List<Single> { 0.1f, 0.2f, 0.3f };
MyTest["Tata"] = new List<Single> { 10f };
MyTest.Add("Tutu", new List<Single> { 1f, 2f, 3f, 4f });
Console.WriteLine(MyTest["Titi"][1]);
MyTest["Tutu"][2] = 15.8f;
Console.WriteLine(MyTest["Tutu"][2]);
try
{
Console.WriteLine(MyTest[1][1]);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadKey(true);
}
}
class MyList<T> : List<List<T>>
{
private List<List<T>> values = new List<List<T>>();
private List<string> indexes = new List<string>();
public List<T> this[string KeyName]
{
get
{
// On ne contrôle pas l'existance, l'erreur standard nous suffit
return values[indexes.IndexOf(KeyName)];
}
set
{
// Si l'index n'existe pas, alors on crée une nouvelle ligne
int idx = indexes.IndexOf(KeyName);
if (idx >= 0)
{
values[idx] = value;
}
else
{
indexes.Add(KeyName);
values.Add(value);
}
}
}
// Interdit l'accès à l'indexeur par défaut
public new List<T> this[int index]
{
get
{
throw new InvalidOperationException();
}
set
{
throw new InvalidOperationException();
}
}
// Pour bien faire, il faut masquer toutes les autres méthodes qui ne vont pas, ou si possible, les enrichir et proposer des surcharges
public new void Add(List<T> value)
{
throw new InvalidOperationException();
}
public void Add(string KeyName, List<T> value)
{
if (indexes.Contains(KeyName))
{
throw new UriFormatException("Cet élément existe déjà...");
}
else
{
this[KeyName] = value;
}
}
}
} |
Partager