C# IDictionary的扩展方法:无法从用法推断方法的类型参数
为了清理大量重复的代码,我尝试实现以下扩展方法:C# IDictionary的扩展方法:无法从用法推断方法的类型参数,c#,generics,extension-methods,C#,Generics,Extension Methods,为了清理大量重复的代码,我尝试实现以下扩展方法: public static void AddIfNotPresent(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value) { if (!dictionary.ContainsKey(key)) { dictionary.Add(key, value); } }
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.addifyNotPresentThis System.Collections.Generic.IDictionary dictionary、TKey、TValue”的类型参数。尝试显式指定类型参数
对此问题的任何解释都将不胜感激 试试这个:
public static void AddIfNotPresent<TKey, TValue>
(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");
}
您的扩展方法不是泛型的,但应该是泛型的,因为扩展方法必须在非泛型顶级类中定义。在我将其作为通用方法之后,下面是相同的代码:
// 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);
}
}
但是,试图编译您实际发布的代码时会显示与您指定的代码不同的错误消息。这表明你还没有发布真正的代码。。。因此,上述情况可能无法解决问题。但是,您发布的带有上述更改的代码可以正常工作。难道不能简单地用它来完成吗
dictionary[key] = value;
如果密钥不存在,则添加密钥/值对;如果存在,则更新值。有关IDictionary的简单用法,请参见。+1。虽然问题更多的是关于为什么有些东西不能编译,而不是关于IDictionaryThanks的正确使用,但我显然对泛型有点耳濡目染。编译器警告真的让我困惑,我本以为方法本身不会编译,而不是调用编译器警告。再次感谢