我有下面的代碼,旨在建立一個字典對象,結構如下Dictionary<string<Dictionary<string, string>
。由於某種原因,每次向它添加項目時,關鍵文本都是正確的,但值(字典)會覆蓋前一個項目。這可能是更好的這樣的解釋:C#:嵌套字典問題
迭代1
- 鍵1,dictionary1
迭代2
- 鍵1,dictionary2
- KEY2,dictionary2
迭代3
鍵1,dictionary3
鍵2,dictionary3
- KEY3,dictionary3
是什麼原因造成這一點,我該如何解決這段代碼來阻止我是否在每個條目中覆蓋字典?
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」實例。 – 2012-08-07 08:19:48
您正在多次添加QueryNameUserQueryString - 這意味着DialectDictionary將具有對同一對象的多個引用。如果更新它,更改將反映在DialectDictionary中的所有項目中 – Charleh 2012-08-07 08:20:37
但是,當它添加到另一個字典對象時,它不應該在當時將該字典的副本添加到該字典中作爲值?我誤解了字典對象的工作原理嗎? – CSharpened 2012-08-07 08:20:52