【发布时间】: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
- ();
- uiItemDictionary = new Dictionary
标签: c# dictionary key overriding gethashcode