Veuillez comparer ces deux codes. Je ne peux pas comprendre pourquoi l'ancien ne travaillait pas alors que le dernier fonctionnait parfaitement.C# Objet en tant que problème clé du dictionnaire
// With loop - not work
for (int i = 0; i < 5; i++)
{
Location l = new Location();
l.Identifier = i.ToString();
_locations.Add(l);
}
////
Dictionary<Location, Route> _paths = new Dictionary<Location, Route>();
foreach (Location loc in _locations)
{
_paths.Add(loc, new Route(loc.Identifier));
}
Location start = new Location();
start.Identifier = "1";
_paths[start].Cost = 0; //raised Key not exists error
Voici version de travail ...
// Without Loop - it work
Location l1 = new Location();
l1.Identifier = "1";
_locations.Add(l1);
Location l2 = new Location();
l2.Identifier = "2";
_locations.Add(l2);
Location l3 = new Location();
l3.Identifier = "3";
_locations.Add(l3);
/////
Dictionary<Location, Route> _paths = new Dictionary<Location, Route>();
foreach (Location loc in _locations)
{
_paths.Add(loc, new Route(loc.Identifier));
}
Location start = new Location();
start.Identifier = "1";
_paths[start].Cost = 0;
Toutes les idées? Merci.
Edit: Lieu Indice
public class Location
{
string _identifier;
public Location()
{
}
public string Identifier
{
get { return this._identifier; }
set { this._identifier=value; }
}
public override string ToString()
{
return _identifier;
}
}
Vous devriez également publier votre classe Location, et regardez ici -> http://stackoverflow.com/questions/634826/using-an-object-as-a-generic-dictionary-key-in-net ;) – digEmAll
Cest juste ... Vous devez également publier la classe Location. Le membre Identifiant de la classe Location est-il une chaîne ou quelque chose d'autre? – Shekhar
@digEmAll - Merci pour le lien. Cela a résolu mon problème. –