Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如果对象具有相同的名称(C#),如何向字典中的键(对象)添加值_C#_Dictionary_Parameters_Key - Fatal编程技术网

如果对象具有相同的名称(C#),如何向字典中的键(对象)添加值

如果对象具有相同的名称(C#),如何向字典中的键(对象)添加值,c#,dictionary,parameters,key,C#,Dictionary,Parameters,Key,所以,我有一本字典叫魔药。我需要检查魔药中的键是否与作为参数传递的对象具有相同的名称。现在我可以这样做了,但我不知道如果item对象和键具有相同的名称,如何向该特定键添加值。此代码适用于对象的第一个实例。但当我添加另一个与键同名的实例对象时,我会得到一个键未找到异常。我知道这两个对象不会是相同的。如何在字典中提取对象引用?还是有别的办法 public static void addItem(Potion item) { if (Potions.Count >0) {

所以,我有一本字典叫魔药。我需要检查魔药中的键是否与作为参数传递的对象具有相同的名称。现在我可以这样做了,但我不知道如果item对象和键具有相同的名称,如何向该特定键添加值。此代码适用于对象的第一个实例。但当我添加另一个与键同名的实例对象时,我会得到一个键未找到异常。我知道这两个对象不会是相同的。如何在字典中提取对象引用?还是有别的办法

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);
    }
 }
公共静态无效添加项(药剂项)
{
如果(药水数量>0)
{
foreach(魔药中的键值对)
{
if(pair.Key.itemName==item.itemName)
{
containsItem=true;
}   
}
if(containsItem)
{
药剂[项目]+=1;
调试日志(药剂[项目]);
containsItem=false;
}
其他的
{       
药剂。添加(第1项);
}
}
其他的
{
药剂。添加(第1项);
}
foreach(魔药中的键值对)
{
Debug.Log(pair.Key.itemName+“:”+pair.Value);
}
}

这不起作用,因为您将要添加的项用作键,并且它不是同一个对象

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

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
药剂密钥=null;
foreach(魔药中的键值对)
{
if(pair.Key.itemName==item.itemName)
{
密钥=配对
}   
}
如果(key!=null):
药剂[钥匙]+=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
药剂密钥=null;
foreach(魔药中的键值对)
{
if(pair.Key.itemName==item.itemName)
{
密钥=配对
}   
}
如果(key!=null):
药剂[钥匙]+=1

我实际上会提供一种替代实现

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];
    }
}

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

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];
    }
}

你使用的是
药剂
作为钥匙,但根据你的密码,对你来说重要的是
itemName
。因此,我建议您将词典改为
。另外,正如所评论的,当使用自定义类时,建议重写
Equals
GetHashCode

您的代码可以是这样的:

 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);
    }
 }
公共静态无效添加项(药剂项)
{
if(药剂容器(项目名称))
药剂[物品.物品名称]+=1;
其他的
药剂。添加(物品。物品名称,1);
foreach(魔药中的键值对)
{
Console.WriteLine(pair.Key+“:”+pair.Value);
}
}

您使用的是
药剂
作为钥匙,但根据您的密码,对您来说重要的是
物品名称
。因此,我建议您将词典改为
。另外,正如所评论的,当使用自定义类时,建议重写
Equals
GetHashCode

您的代码可以是这样的:

 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);
    }
 }
公共静态无效添加项(药剂项)
{
if(药剂容器(项目名称))
药剂[物品.物品名称]+=1;
其他的
药剂。添加(物品。物品名称,1);
foreach(魔药中的键值对)
{
Console.WriteLine(pair.Key+“:”+pair.Value);
}
}

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

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.    
}           
职业药剂{
公共字符串名称;
公共int颜色;
}
类PotionNameEqualityComparer:IEqualityComparer{
公共布尔等于(药剂p1,药剂p2){
返回p1.Name.Equals(p2.Name);
}
公共整数GetHashCode(药剂p1){
返回p1.Name.GetHashCode();
}
}
void Main(){
var d=新字典(新PotionNameEqualityComparer());
var p1=新药剂(){Name=“Health”,Color=1};
var p2=新药剂(){Name=“Health”,Color=2};
d、 添加(p1,1);
d[p2]++;//有效,现在您有两种健康药水。
//当然,字典中的实际实例是p1;
//p2未存储在字典中。
}           

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

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.    
}           
职业药剂{
公共字符串名称;
公共int颜色;
}
类PotionNameEqualityComparer:IEqualityComparer{
公共布尔等于(药剂p1,药剂p2){
返回p1.Name.Equals(p2.Name);
}
公共整数GetHashCode(药剂p1){
返回p1.Name.GetHashCode();
}
}
void Main(){
var d=新字典(新PotionNameEqualityComparer());
var p1=新药剂(){Name=“Health”,Color=1};
var p2=新药剂(){Name=“Health”,Color=2};
d、 添加(p1,1);
d[p2]++;//有效,现在您有两种健康药水。
//当然,字典中的实际实例是p1;
//p2未存储在字典中。
}           

也许你的
魔药
类应该覆盖
Equals
GetHashCode
(因此字典认为同名魔药是相同的)-或者您可以将字典更改为
,其中
字符串
键是药水的
项目名称
?您的第一种方法有效吗?除了名称,对象也不相同。我真的需要钥匙来做药水这会有用的。。某种程度上。看看我的答案。也许你的
药剂
类应该覆盖
等于