给出以下代码:
Hashtable main = new Hashtable();
Hashtable inner = new Hashtable();
ArrayList innerList = new ArrayList();
innerList.Add(1);
inner.Add("list", innerList);
main.Add("inner", inner);
Hashtable second = (Hashtable)main.Clone();
((ArrayList)((Hashtable)second["inner"])["list"])[0] = 2;
为什么数组中的值在“main”Hashtable中从1变为2,因为更改是在克隆上进行的?
答案 0 :(得分:6)
您克隆了Hashtable
,而不是其内容。
答案 1 :(得分:0)
谢谢你的帮助,伙计们。我最终得到了这个解决方案:
Hashtable clone(Hashtable input)
{
Hashtable ret = new Hashtable();
foreach (DictionaryEntry dictionaryEntry in input)
{
if (dictionaryEntry.Value is string)
{
ret.Add(dictionaryEntry.Key, new string(dictionaryEntry.Value.ToString().ToCharArray()));
}
else if (dictionaryEntry.Value is Hashtable)
{
ret.Add(dictionaryEntry.Key, clone((Hashtable)dictionaryEntry.Value));
}
else if (dictionaryEntry.Value is ArrayList)
{
ret.Add(dictionaryEntry.Key, new ArrayList((ArrayList)dictionaryEntry.Value));
}
}
return ret;
}