ich habe eine kleine Beispielmethode, die wie folgt aussieht:
public bool removeApplicationAtIndex(int index)
{
// Look if the index makes sense to prevent Exceptions.
// FIXME: shouldn't it be Count<index, since Count==index provides an OutOfBoundsException?
// FIXME: shouldn't the index be checked to be larger than -1?
if(this.applicationsDictionary.Count ≤ index)
{
// Doesn't make sense, stop trying.
return false;
}
// Gather all keys in an array to determine which key represents this index.
System.Collections.Generic.Dictionary<long,string>.KeyCollection kc = this.applicationsDictionary.Keys;
int current = 0;
foreach(long item in kc)
{
if(current == index)
{
// This key matches this index, so remove the object with this key.
this.applicationsDictionary.Remove(item);
return true;
}
current++;
}
// Index not found. Should never happen, but who knows.
return false;
}
Jetzt möchte ich dieselbe Funktionalität, also ein Mapping zwischen einem Array-Index und einem Dictionary-Key, auch für andere Dictionaries hinbekommen.
Mein erster Ansatz ist, die spezialisierten Methoden aufzuweichen und damit eine allgemeine Methode aufzurufen.
public bool removeApplicationAtIndex(int index)
{
return removeValueInDictAtIndex(this.applicationsDictionary, index);
}
public bool removeValueInDictAtIndex(System.Collections.Generic.Dictionary<object,object> dict, int index)
{
...
if(dict.Count ≤ index)
...
System.Collections.Generic.Dictionary<object,object>.KeyCollection kc = dict.Keys;
...
foreach(var item in kc)
...
dict.Remove(item);
...
}
Nur leider habe ich unterschiedliche Dictionaries.
Eines arbeitet mit <string,string>, eines mit <long,string>, eines mit <string,long> und so weiter. Deshalb ist dieser Ansatz nicht praktikabel.
Wie kann ich es realisieren, dass ich obiges Gewirr (das vermutlich auch ein paar Fehler enthält, siehe //FIXME: ^^) nur einmalig tippen muss und trotzdem unterschiedliche Dictionaries abgearbeitet werden können?