foreach (Ant ant in state.MyAnts)
{
if (m_foodTasks.ContainsKey(ant))
{
...
通過調試我可以看到有一個螞蟻裏面m_foodTasks完全相同的值。所以我會假設它比較了參考地址..(對嗎?)C#hashtable ContainsKey返回false,當我知道它有一個關鍵的條目
我該如何讓它與價值進行比較?閱讀答案後
編輯:
太多的信息... 我需要一段時間來研究的,但這裏是什麼類的螞蟻已經有了(我不能說所有的東西是什麼):
public class Location : IEquatable<Location> {
/// <summary>
/// Gets the row of this location.
/// </summary>
public int Row { get; private set; }
/// <summary>
/// Gets the column of this location.
/// </summary>
public int Col { get; private set; }
public Location (int row, int col) {
this.Row = row;
this.Col = col;
}
public override bool Equals (object obj) {
if (ReferenceEquals (null, obj))
return false;
if (ReferenceEquals (this, obj))
return true;
if (obj.GetType() != typeof (Location))
return false;
return Equals ((Location) obj);
}
public bool Equals (Location other) {
if (ReferenceEquals (null, other))
return false;
if (ReferenceEquals (this, other))
return true;
return other.Row == this.Row && other.Col == this.Col;
}
public override int GetHashCode()
{
unchecked {
return (this.Row * 397)^this.Col;
}
}
}
public class TeamLocation : Location, IEquatable<TeamLocation> {
/// <summary>
/// Gets the team of this ant.
/// </summary>
public int Team { get; private set; }
public TeamLocation (int row, int col, int team) : base (row, col) {
this.Team = team;
}
public bool Equals(TeamLocation other) {
return base.Equals (other) && other.Team == Team;
}
public override int GetHashCode()
{
unchecked {
int result = this.Col;
result = (result * 397)^this.Row;
result = (result * 397)^this.Team;
return result;
}
}
}
public class Ant : TeamLocation, IEquatable<Ant> {
public Ant (int row, int col, int team) : base (row, col, team) {
}
public bool Equals (Ant other) {
return base.Equals (other);
}
}
類Ant是不是我的,但我可以看到它已經重寫了一些Equals和GetHashCode的方法,他們從IEquatable推導以及,我沒有得到任何這些東西.. Theres沒有辦法簡單使它比較該死的關鍵價值?聽起來很簡單,不是嗎? – Icebone1000
查看我的上次編輯 –
@ Icebone1000您是否檢查過以確保'GetHashCode'返回相同的值,您認爲這兩個項目是「相等的」。如果他們不這樣做,那麼他們在字典的眼中就是不平等的。使用GetHashCode跳過這些循環的原因是,您*不需要將您搜索的值與所有鍵值進行比較。你只需要將它與具有相同散列碼的值進行比較(這應該是一小部分),這使得它*效率更高。如果您想簡化效率,請使用不同的數據結構。 – Servy