简体   繁体   English

C#字典键覆盖未找到键

[英]C# Dictionary Key override not finding key

I am trying to search through a dictionary with TryGetValue using an object as a key. 我试图通过使用对象作为键的TryGetValue搜索字典。 I have overridden the GetHashCode which I thought would be what was required to set how the key is generated for a dictionary. 我已经重写了GetHashCode,我认为这是设置字典生成键的方式所必需的。 The Item class below is the key for the dictionary. 下面的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();
   } 
      [...]
   }

From a different class I use 'TryGetValue(Item,GameObject)' to see if the item exists in the dictionary but even when there are multiple Item's in the dictionary with the same name and itemType, it does not find the key. 从另一个类中,我使用“ 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);
    }
  [...]
}

Any suggestions? 有什么建议么? Is there something else I need to override? 还有什么我需要覆盖的吗?

Thanks, 谢谢,

Chris 克里斯

Try overriding Equals as such: 尝试这样覆盖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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM