【发布时间】:2012-08-07 08:17:12
【问题描述】:
我有下面的代码,它旨在构建一个具有以下构造的字典对象Dictionary<string<Dictionary<string, string>。出于某种原因,每次我向其中添加一个项目时,关键文本都是正确的,但值(字典)会覆盖前一个。最好这样解释:
迭代 1
- key1,字典1
迭代 2
- key1,字典2
- key2,字典2
迭代 3
key1,字典3
key2,字典3
- key3,字典3
是什么原因造成的?如何修复此代码以阻止它覆盖每个条目中的字典?
QueryNameUserQueryString = new Dictionary<string, string>();
DialectDictionary = new Dictionary<string, Dictionary<string, string>>();
while (dataBaseConnection.NextRecord())
{
if (QueryNameUserQueryString != null)
{
QueryNameUserQueryString.Clear();
}
string dialect = dataBaseConnection.GetFieldById (0);
//If no dialect then carry out next iteration
if (String.IsNullOrEmpty (dialect))
{
continue;
}
try
{
dataBaseConnection2.ExecutePureSqlQuery ("SELECT * FROM " + sqlFactoryTable + " WHERE SQL_FACTORY_DIALECT = '" + dialect + "'");
}
catch
{
dataBaseConnection.Close();
dataBaseConnection2.Close();
throw;
}
//Do we have query strings for this dialect?
if (!dataBaseConnection2.HasRows())
{
continue;
}
//loop through query strings
while (dataBaseConnection2.NextRecord())
{
string queryName = dataBaseConnection2.GetFieldById (2);
string queryString = dataBaseConnection2.GetFieldById (3);
string user = dataBaseConnection2.GetFieldById (4);
//create composite key for dictionary
string compositeKey = dialect + "," + queryName + "," + user;
if (QueryNameUserQueryString != null)
{
//Construct our query string dictionary
QueryNameUserQueryString.Add (compositeKey, queryString);
}
}
//If we have a query string dictionary
if (QueryNameUserQueryString != null)
{
//Ensure m_dialect dictionary is not null
if (DialectDictionary != null)
{
//Construct our dictionary entry for this dialect
DialectDictionary.Add (dialect, QueryNameUserQueryString);
}
}
}
}
【问题讨论】:
-
您似乎在每次迭代中都使用
QueryNameUserQueryString的相同实例。 -
您正在多次添加 QueryNameUserQueryString - 这意味着 DialectDictionary 将对同一个对象有多个引用。如果您更新它,更改将反映在 DialectDictionary 中的所有项目中
-
但是当它被添加到另一个字典对象时,它不应该将当时的字典副本作为值添加到其中吗?我是否误解了字典对象的工作原理?
-
不 - 它是通过引用传递的
-
JleruOHeP 的回答作为一个开始。 =) 但是,实际上 - 将变量放在 while 范围内。这样你就限制了它的范围,所以它每次迭代只能存在一次,而不是所有迭代。
标签: c# dictionary