📜  如何在C#中创建Hashtable的浅表副本

📅  最后修改于: 2021-05-29 18:36:40             🧑  作者: Mango

Hashtable.Clone方法用于创建Hashtable的浅表副本。当我们进行浅表复制时,无论集合的类型如何,都将仅复制集合的元素,它不会复制引用所引用的对象。基本上,它将创建一个新对象,并且该对象指向原始引用。

句法:

HashtableName.Clone();

下面的示例说明了此方法的用法。

示例1:创建Hashtable类类型的对象H1,该对象在System.Collections命名空间中预定义。然后,我们使用Hashtable添加键和类型为字符串的值。添加方法。 Hashtable.clone方法用于创建H1的浅表副本。我们使用foreach循环显示ShallowH1的元素。 DictionaryEntry属性用于设置或获取键的值,该值对成对排列。

// C# Program to demonstrate
// the Hashtable.Clone Method
using System;
using System.Collections;
  
namespace hashtable {
  
class GFG {
  
    // Main Method
    public static void Main(string[] args)
    {
        // Declaring a Hashtable named H1
        // Calls the default constructor
        Hashtable H1 = new Hashtable();
  
        // Adding keys and values
        // to the hashtable
        H1.Add("1", "This");
        H1.Add("2", "is");
        H1.Add("3", "a");
        H1.Add("4", "Hash");
        H1.Add("5", "Table");
  
        // Creating a shallow copy of H1
        Hashtable ShallowH1 = new Hashtable();
        ShallowH1 = (Hashtable)H1.Clone();
  
        // Displaying values of key, value pairs
        // Using DictionaryEntry which is predefined
        foreach(DictionaryEntry item in ShallowH1)
        {
            Console.WriteLine("Key " + item.Key + 
                         " Value " + item.Value);
        }
    }
}
}
输出:
Key 5 Value Table
Key 1 Value This
Key 4 Value Hash
Key 3 Value a
Key 2 Value is

示例2:现在让我们尝试对浅表副本进行一些更改。如下面的代码所示,浅表副本的更改不会反映在原始哈希表中。

// C# Program to demonstrate
// the Hashtable.Clone Method
using System;
using System.Collections;
  
namespace hashtable2 {
  
class GFG {
  
    // Main Method
    public static void Main(String[] args)
    {
        // Declaring a Hashtable
        // Calls the constructor
        Hashtable H1 = new Hashtable();
  
        // Add the values to H1
        H1.Add("1", "Orange");
        H1.Add("2", "Apple");
        H1.Add("3", "Blueberry");
  
        // Create a shallow copy
        Hashtable H2 = new Hashtable();
        H2 = (Hashtable)H1.Clone();
  
        // Making changes in the shallow copy
        H2.Add("4", "Mango");
        H2.Remove("1");
  
        // Displaying original Hashtable
        foreach(DictionaryEntry item in H1)
            Console.WriteLine("Key {0} Value {1}",
                            item.Key, item.Value);
  
        Console.WriteLine();
  
        // Displaying shallow copy
        // of the Hashtable
        foreach(DictionaryEntry item in H2)
            Console.WriteLine("Key {0} Value {1}", 
                            item.Key, item.Value);
    }
}
}
输出:
Key 3 Value Blueberry
Key 2 Value Apple
Key 1 Value Orange

Key 4 Value Mango
Key 3 Value Blueberry
Key 2 Value Apple

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.hashtable.clone?view=netframework-4.7.2#System_Collections_Hashtable_Clone