C#Dictionary键覆盖未找到键

时间:2014-03-20 05:58:39

标签: c# dictionary key override gethashcode

我正在尝试使用对象作为键来搜索TryGetValue的字典。我已经覆盖了GetHashCode,我认为这将是设置如何为字典生成密钥所需的内容。下面的Item类是字典的关键字。

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;

public class Item : MonoBehaviour
{
   int id;
   string name;
   string itemType;

   public Item(string name, int id, string itemType)
   {
       this.name = name;
       this.id = id;
       this.itemType = itemType;
   }
   public override bool Equals(object obj)
   {
       if (obj == null)
        return false;
       Item myItem = (Item)obj;
       if (myItem == null)
        return false;

       return (name == myItem.name) && (itemType == myItem.itemType);
   }
   public override int GetHashCode()
   {        
       return (this.name + this.itemType).GetHashCode();
   } 
      [...]
   }

从另一个类我使用'TryGetValue(Item,GameObject)'来查看该项是否存在于字典中,但即使字典中有多个具有相同名称和itemType的Item,它也找不到该键。

public void UIItemCreate(Item item, GameObject itemGameObject)
{
    GameObject go = null;

    uiItemDictionary.TryGetValue (item, out go); 
    if(go == null)
    { 
     uiItemDictionary.Add(item,itemGameObject);
     go = NGUITools.AddChild(this.gameObject,itemGameObject);
    }
  [...]
}

有什么建议吗?还有其他我需要覆盖的东西吗?

谢谢,

克里斯

1 个答案:

答案 0 :(得分:1)

尝试覆盖Equals

public override bool Equals(object obj)
{
    var myItem = obj as Item;
    return !ReferenceEquals(myItem, null) && Equals(myItem);
}

public bool Equals(Item myItem)
{
    return string.Equals(name, myItem.name, StringComparison.Ordinal) && string.Equals(itemType, myItem.itemType, StringComparison.Ordinal);
}