【发布时间】:2013-07-11 17:34:32
【问题描述】:
运行以下代码时,有时会出现以下错误:
System.ArgumentException: An item with the same key has already been added.
at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at Interfaces.InterfaceBase.GetSettings()
我正在使用以下代码:
For Each dr As DataRow In dsData.Tables("tblData").Rows
If InterfaceSettings.ContainsKey(dr("SettingsName").ToString.Trim) = False Then
InterfaceSettings.Add(dr("SettingsName").ToString.Trim, dr("SettingsValue").ToString.Trim)
End If
Next
我在数据库表中没有重复项。知道为什么这会失败吗?
提前感谢您的帮助。
【问题讨论】:
-
您是否确认在 dr("SettingsName") 中没有重复项并且它们都不是 null 或 String.Empty?如果您有一两个空的项目,它会添加一个副本。
-
很遗憾,您发布的异常与代码无关。如果您查看堆栈跟踪,您将看到异常是由调用 Dictionary.Insert 而不是 Dictionary.Add 生成的。我将搜索该过程的其余部分,以查看您在哪里调用 Dictionary Insert。
-
@competent_tech -
.Add在内部调用.Insert:public void Add(TKey key, TValue value) { Insert(key, value, true); }---Insert是内部私有方法 -
@J...:我理解,但除非编译器优化生成的代码以删除对 Add 的引用,我不相信这种情况,堆栈跟踪将始终包含调用先添加:在 System.Collections.Generic.Dictionary
2.Insert(TKey key, TValue value, Boolean add) at System.Collections.Generic.Dictionary2.Add(TKey key, TValue value) -
@competent_tech - 不,如果异常是通过调用另一个类中的方法引发的,则不会。在这种情况下,他的代码调用了
.GetSettings(),其中包含添加到字典中的代码。无法在用户代码中调用.Insert- 它是 TDictionary 中的私有方法,无法访问。
标签: vb.net