为了清理大量重复的代码,我尝试实现下面的扩展方法:
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值)的类型参数。尝试明确指定类型参数。
对此主题的任何启发都将不胜感激!
答案 0 :(得分:6)
您的扩展方法不是通用的,但应该是,因为必须在非通用顶级类中定义扩展方法。在我将其作为通用方法之后,这是相同的代码:
// 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);
}
}
但是,尝试编译实际发布的代码会给出与您指定的代码不同的错误消息。这表明你还没有发布真正的代码......所以上面的内容可能无法解决问题。但是,您使用上述更改发布的代码可以正常工作。
答案 1 :(得分:5)
这不能简单地用这个来完成吗?
dictionary[key] = value;
如果密钥不存在,则添加密钥/值对;如果密钥不存在,则更新值。请参阅Dictionary<TKey,TValue>.Item
。
答案 2 :(得分:4)
试试这个:
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");
}