【问题标题】:C# Dictionary Key override not finding keyC# 字典键覆盖未找到键
【发布时间】:2014-03-20 05:58:38
【问题描述】:

我正在尝试使用对象作为键来搜索带有 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 的项目,它也找不到密钥。

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);
    }
  [...]
}

有什么建议吗?还有什么我需要覆盖的吗?

谢谢,

克里斯

【问题讨论】:

  • 您使用的字典的确切类型是什么?
  • System.Collection.Generic.Dictionary uiItemDictionary = new Dictionary();

标签: c# dictionary key overriding gethashcode


【解决方案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);
}

【讨论】:

  • 这似乎有效。你能解释一下为什么我的覆盖 bool Equals() 不够吗?只是想了解为什么这可能是必要的,而不是我的替代。
  • 这里object.Equals 用于相等性检查,这是在使用哈希码在字典中查找候选键之后完成的。然后只需要调用Equals 方法来断言它们实际上是相等的。
猜你喜欢
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多