簡體   English   中英

.NET哈希表克隆

[英].NET Hashtable clone

給出以下代碼:

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;

為什么數組的值在“主”哈希表中從1變為2,因為更改是在克隆上進行的?

您克隆了Hashtable ,而不是其內容。

伙計們,謝謝您的幫助。 我最終得到了這個解決方案:

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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM