Given the following code:
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;
Why does the value within the array change from 1 to 2 in the "main" Hashtable, as the change was made on a clone ?
您克隆了Hashtable
,而不是其内容。
Thanks for your help, guys. I ended up with this solution:
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.