聚合字典

本文关键字:字典 | 更新日期: 2023-09-27 18:26:00

为了聚合某些值的出现次数,我使用了dictionary<valueName:string, counter:int>,我不知道确切的值。所以我写了一个方法SetOrIncrement,它应该像一样使用

myDictionary.SetOrIncrement(name, 1);

但是,VisualStudio的

"字典不包含的定义"SetOrIncrement"且没有接受找不到"Dictionary"类型的第一个参数。"

有人能告诉我原因是什么吗?

这是SetAndIncrement方法:

public static class ExtensionMethods
{
    public static int SetOrIncrement<TKey, int>(this Dictionary<TKey, int> dict, TKey key, int set) {
        int value;
        if (!dict.TryGetValue(key, out value)) {
           dict.Add(key, set);
           return set;
        }
        dict[key] = ++value;
        return value;
    }
}

聚合字典

您的扩展方法编译正确吗?当我试图编译它时,我得到:"类型参数声明必须是标识符而不是类型"。

原因是在这一行:

public static int SetOrIncrement<TKey, int>(this Dictionary<TKey, int> dict, TKey key, int set) {

该方法的通用参数中的CCD_ 4无效。相反,这应该有效:

public static int SetOrIncrement<TKey>(this Dictionary<TKey, int> dict, TKey key, int set) {

原因是TKey是唯一变化的类型。int总是相同的,因此不是泛型参数。

试试这个:

void Main()
{
    var dict = new Dictionary<string, int>();
    dict.SetOrIncrement("qwe", 1);
}
// Define other methods and classes here
public static class ExtensionMethods
{
    public static int SetOrIncrement<TKey>(this Dictionary<TKey, int> dict, TKey key, int set)
    {
        int value;
        if (!dict.TryGetValue(key, out value)) {
           dict.Add(key, set);
           return set;
        }
        dict[key] = ++value;
        return value;
    }
}