修改特定键的哈希表值

  • 本文关键字:哈希表 修改 c#
  • 更新时间 :
  • 英文 :


我需要增加Hashtable中特定键的值,这是我的代码(我想在函数期间创建Hashtable,我希望表格是这样的 - <string><int>

(:
public void getMssg(string ipSend, string mssg, Hashtable table)
{
    if (table.Contains(ipSend))
        table[ipSend]++;        //error
}

顺便问一下,我可以像上面写的那样定义一个Hashtable吗?

public void getMssg(string ipSend, string mssg, Hashtable table)
{
    if (table.Contains(ipSend))
    {
        int value = (int)table[ipSend];
        table[ipSend] = value + 1;
    }
}

在我看来,字典方法会好得多,因为它是类型安全的并且消除了强制转换。哈希表不适合这种用法。举个例子:

public void getMssg(string ipSend, string mssg, Dictionary<string,int> table)
{
    if (table.ContainsKey(ipSend))
        table[ipSend] += 1;
    else
        table.Add(ipSend, 1);
}

我按照@mjwills的建议更新了上面的代码:TryGetValue优于ContainsKey:

public void getMssg(string ipSend, string mssg, IDictionary<string, int> table)
{
    int result;
    if(!table.TryGetValue(ipSend, out result))
        result = 0;
    table[ipSend] = result + 1;
}

请改用Dictionary<string, int>

public void getMssg(string ipSend, IDictionary<string, int> table)
{
    int result;
    if(!table.TryGetValue(ipSend, out result))
        result = 0; // do something if the key is not found
    table[ipSend] = ++result;
}

最新更新