如果键不存在,用于添加的 IDictionary 扩展方法

IDictionary Extension method for Adding if key not present

This old answer建议为此做一个扩展方法,但答案是9年前的,所以C#可能从那时起就不同了,或者我不明白实现。

我目前正在尝试这个:

public static void AddIfNotPresent(this IDictionary<TKey, TValue> dict, TKey key, TValue value)
{
    if (!dict.ContainsKey(key))
    {
        dict.Add(value);
    }
}

...但是 Visual Studio 表示 "The type or namespace TKey cannot be found...",值相同...为什么我不能将这些任意类型添加到扩展方法中?

您的 AddIfNotPresent 没有定义那些通用的 types/arguments (AddIfNotPresent<TKey, TValue>)。该答案遗漏了打字错误。

TKeyTValue 应该是 AddIfNotPresent 的类型参数,AddIfNotPresent 应该在静态 class.

中定义
void Main()
{
    var dictionary = new Dictionary<string, string>();
    dictionary.AddIfNotPresent("key", "value");
    Console.WriteLine($"{dictionary.First().Key} = {dictionary.First().Value}");

    // Output: key = value
}

public static class DictionaryExtensions
{
    public static void AddIfNotPresent<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, TValue value)
    {
        if (!dict.ContainsKey(key))
        {
            dict.Add(key, value);
        }
    }
}