0

所以,我有一本名为 Potions 的字典。我需要检查药水中的键是否与作为参数传递的对象同名。现在我能够做到这一点,但如果项目对象和键具有相同的名称,我无法弄清楚如何向该特定键添加值。此代码适用于对象的第一个实例。但是当我添加另一个与键同名的实例对象时,我得到了一个未找到键的异常。我知道这两个对象不会相同。如何在字典中提取对象引用?还是有其他方法?

public static void addItem(Potion item)
 {
    if (Potions.Count >0)
    {
        foreach(KeyValuePair<Potion,int> pair in Potions)
        {
            if (pair.Key.itemName == item.itemName)
            {
            containsItem = true;
            }   
        }
        if (containsItem)
        {
        Potions[item] += 1;
        Debug.Log (Potions[item]);
        containsItem = false;
        }
        else
            {       
            Potions.Add(item,1);
            }
    }
    else
    {
    Potions.Add (item,1);
    }

    foreach(KeyValuePair<Potion,int> pair in Potions)
    {
        Debug.Log (pair.Key.itemName + " : " + pair.Value);
    }
 }
4

4 回答 4

3

我实际上会提供一个替代实现。

enum Potion
{
    Health,
    Mana
}

class PotionBag
{
    readonly int[] _potions = new int[Enum.GetValues(typeof(Potion)).Length];

    public void Add(Potion potion)
    {
        _potions[(int)potion]++;
    }

    public void Use(Potion potion)
    {
        if (GetCount(potion) == 0)
            throw new InvalidOperationException();
        _potions[(int)potion]--;
    }

    public int GetCount(Potion potion)
    {
        return _potions[(int)potion];
    }
}
于 2012-08-31T03:08:36.107 回答
1

这是行不通的,因为您将添加的项目用作键,并且它不是同一个对象。

为什么不将密钥保存在占位符中,然后在循环之后查找它?

Potion key = null;
foreach(KeyValuePair<Potion,int> pair in Potions)
    {
        if (pair.Key.itemName == item.itemName)
        {
         key = pair.Key
        }   
    }

if(key != null):
    Potions[key] += 1
于 2012-08-31T03:04:28.933 回答
1

您正在Potion用作密钥,但根据您的代码,对您来说重要的是itemName. 因此,我建议您将字典更改为<string, int>. 此外,正如评论的那样,在使用自定义类时,建议覆盖EqualsGetHashCode.

您的代码可能是这样的:

 public static void addItem(Potion item)
 {
    if(Potions.ContainsKey(item.itemName))
        Potions[item.itemName] += 1;
    else
        Potions.Add (item.itemName,1);

    foreach(KeyValuePair<string,int> pair in Potions)
    {
        Console.WriteLine(pair.Key + " : " + pair.Value);
    }
 }
于 2012-08-31T03:09:17.870 回答
1

您可以覆盖Equalsand GetHashCode,但这可能有其他含义。相反,您可以IEqualityComparer在创建字典时使用 an,如下所示:

class Potion {
    public string Name;
    public int Color;
}

class PotionNameEqualityComparer : IEqualityComparer<Potion> {
    public bool Equals(Potion p1, Potion p2) {
        return p1.Name.Equals(p2.Name);
    }
    public int GetHashCode(Potion p1) {
        return p1.Name.GetHashCode();
    }
}

void Main() {
    var d = new Dictionary<Potion, int>(new PotionNameEqualityComparer());
    var p1 = new Potion() { Name = "Health", Color = 1 };
    var p2 = new Potion() { Name = "Health", Color = 2 };
    d.Add(p1, 1);
    d[p2]++; // works, and now you have two health potions. 
             // Of course, the actual instance in the dictionary is p1; 
             // p2 is not stored in the dictionary.    
}           
于 2012-08-31T03:24:41.853 回答