IDictionary的扩展方法< t,k> :无法从用法推断出方法的类型参数

StackOverflow https://stackoverflow.com/questions/1615687

  •  06-07-2019
  •  | 
  •  

为了清理大量重复的代码,我尝试实现下面的扩展方法:

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

    public static void Test()
    {
        IDictionary<string, string> test = new Dictionary<string, string>();
        test.AddIfNotPresent("hi", "mom");
    }

在扩展方法调用期间导致编译器错误:

无法从用法推断出方法'Util.Test.AddIfNotPresent(此System.Collections.Generic.IDictionary字典,TKey键,TValue值)的类型参数。尝试明确指定类型参数。

对此主题的任何启发都将不胜感激!

有帮助吗?

解决方案

您的扩展方法不是通用的,但应该是,因为必须在非通用顶级类中定义扩展方法。在我将其作为通用方法之后,这是相同的代码:

// Note the type parameters after the method name
public static void AddIfNotPresent<TKey, TValue>
    (this IDictionary<TKey, TValue> dictionary, TKey key, TValue value)
{
    if (!dictionary.ContainsKey(key))
    {
        dictionary.Add(key, value);
    }
}

但是,尝试编译实际发布的代码会给出与您指定的代码不同的错误消息。这表明你还没有发布真正的代码......所以上面的内容可能无法解决问题。但是,您使用上述更改发布的代码可以正常工作。

scroll top