Dvl*_*lpr 0 c# dictionary list add
我有如下代码:
static void Main(string[] args)
{
List<Dictionary<string, string>> abc = new List<Dictionary<string, string>>();
Dictionary<string, string> xyz = new Dictionary<string, string>();
Dictionary<string, string> klm = new Dictionary<string, string>();
xyz.Add("xyz_1", "4");
xyz.Add("xyz_2", "5");
klm.Add("klm_1", "9");
klm.Add("klm_2", "8");
abc.Add(xyz);
xyz.Clear();
/*after this code xyz clear in my abc list. Why ?*/
abc.Add(klm);
}
Run Code Online (Sandbox Code Playgroud)
我创建字典列表。然后,我将字典添加到此列表中。但是添加字典后,具有清除功能的字典将为空,而不是从列表中删除。通常,我的“ abc”列表应包含xyz和klm字典及其值。但是运行clearfunction时xyz值计数将为0。我该如何预防该站?
我不是因为xyz添加了参考abc。使用:
abc.Add(new Dictionary<string, string>(xyz));
Run Code Online (Sandbox Code Playgroud)