【问题标题】:.NET Hashtable clone.NET 哈希表克隆
【发布时间】:2011-02-07 19:15:00
【问题描述】:

给定以下代码:

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,因为更改是在克隆上进行的?

【问题讨论】:

    标签: c# .net hashtable clone


    【解决方案1】:

    你克隆了Hashtable,而不是它的内容。

    【讨论】:

    • 感谢您的提示。我也尝试过使用新的 Hashtable(main),它仍然是一样的。你能建议一个适当的方法吗?谢谢。
    • 如果你想进行深度克隆,你必须手动迭代原始集合,克隆每个项目,然后将其插入到新集合中(你必须自己创建为空)。
    【解决方案2】:

    谢谢你们的帮助,伙计们。我最终得到了这个解决方案:

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

    【讨论】:

    • 这可能适合您的情况,但请注意 ArrayList 仍然是浅克隆的。如果 arraylist 包含对象,则此处仍然存在不规则的深+浅克隆。
    • 似乎是一个不错的扩展方法候选者。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-19
    • 2011-01-28
    • 1970-01-01
    • 1970-01-01
    • 2012-11-24
    • 1970-01-01
    • 2011-10-30
    相关资源
    最近更新 更多