IDictionary的扩展方法:方法的类型参数无法从用法中推断出来
为了清理大量重复的代码,我尝试实现下面的扩展方法:
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(this System.Collections.Generic) 的类型参数.IDictionary 字典、TKey 键、TValue 值)' 无法从用法中推断出来。尝试显式指定类型参数。
关于这个主题的任何说明将不胜感激!
In an attempt to clean up a lot of repeated code, I tried implementing the extension method below:
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");
}
Results in a compiler error during the extension method call of:
The type arguments for method 'Util.Test.AddIfNotPresent(this System.Collections.Generic.IDictionary dictionary, TKey key, TValue value)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
Any light on this subject would be much appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的扩展方法不是通用的,但应该是通用的,因为扩展方法必须在非通用顶级类中定义。这是我将其设为通用方法后的相同代码:
但是,尝试编译您实际发布的代码会给出与您指定的错误消息不同的错误消息。这表明您尚未发布真实代码......因此上述内容可能无法解决问题。但是,您发布的经过上述更改的代码工作正常。
Your extension method isn't generic, but should be, as extension methods must be defined in non-generic top level classes. Here's the same code after I've made it a generic method:
However, trying to compile the code you actually posted gives a different error message from the one you specified. That suggests that you haven't posted the real code... and so the above may not fix things anyway. However, the code you posted with the above change works fine.
简单的用这个就可以完成吗?
如果键不存在,它会添加键/值对;如果存在,它会更新值。请参阅
字典.Item
。Can't this be done simply with this?
It adds the key/value pair if the key doesn't exist, or updates the value if it does. See
Dictionary<TKey,TValue>.Item
.试试这个:
Try this: