c# - C# Dictionary 在 C# in depth 2nd Edition 中是如何使用的?

标签 c# dictionary

我在 Jon Skeet 的 Depth 2nd Edition 中看到了以下 C# 代码,但我不明白它是如何工作的。

Dictionary<string,int> frequencies;
frequencies = new Dictionary<string,int>();
string[] words = Regex.Split(text, @"\W+");
foreach (string word in words)
{
    if (frequencies.ContainsKey(word))
    {
        frequencies[word]++;
    }
    else
    {
        frequencies[word] = 1;
    }
}

具体如何将“word”键添加到字典中?如我所见,创建了一个名为频率的新字典,它是空的。然后有一种方法可以使用 Regex.Split 将名为 text 的字符串拆分为字符串数组。到目前为止一切都很好。接下来有一个循环遍历数组的 foreach 循环,但下一部分让我感到困惑,它正在检查频率是否包含特定单词,如果包含则将其值增加 1,或者如果它还没有value 将其设置为 1。但是字典如何首先填充“word”键以允许对其进行检查?

看起来是发生在这一行

frequencies[word] = 1;

但我在任何地方都找不到说明指定字典对象后跟方括号和对值的赋值也会填充键的引用。我认为您需要使用字典实例的 add 方法或在初始化字典时这样做。

如果我是正确的,这个 Action 的名称是什么?

最佳答案

frequencies[word] = 1;

和调用一样

frequencies.Add(word, 1);

如果关键字不存在。否则,您将覆盖该值。

当您调用 [something] 时在字典上,您可以通过键获得一个值 something .设置也是如此。设置值时,您可以调用 dictionary[key] = value .

使用的函数是 [] operator (brackets operator) .

我进入对象浏览器并找到了关于 [] 的信息通用字典的运算符:

public TValue this[TKey key] { get; set; } Member of System.Collections.Generic.Dictionary<TKey, TValue>

Summary: Gets or sets the value associated with the specified key.

Parameters: key: The key of the value to get or set.

Return Values: The value associated with the specified key. If the specified key is not found, a get operation throws a System.Collections.Generic.KeyNotFoundException, and a set operation creates a new element with the specified key.

Exceptions: System.ArgumentNullException: key is null. System.Collections.Generic.KeyNotFoundException: The property is retrieved and key does not exist in the collection.

关于c# - C# Dictionary 在 C# in depth 2nd Edition 中是如何使用的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18892882/

相关文章:

javascript - 序列化 DateTime 属性以在 javascript 中工作

python - 对数据帧字典中的每个数据帧进行排序

python - 如何制作一个以 pandas 数据帧列表作为值的字典?

c# 字符串日期格式从 d.M.yyyy 到 yyyy-MM-dd

c# - 连接到安全网络服务时出错!

c# - 如果我选择第一项,组合框不显示所选项目

python - 如何比较嵌套字典?

Python 字典到 URL 参数

python - 字典文本以相同字母开头和结尾

c# - 如何避免重复的 "using"代码