📜  C#|将Hashtable元素复制到数组实例

📅  最后修改于: 2021-05-30 01:38:43             🧑  作者: Mango

Hashtable.CopyTo(Array,Int32)方法用于将Hashtable的元素复制到指定索引处的一维Array实例。

句法:

public virtual void CopyTo (Array array, int arrayIndex);

参数:

例外情况:

  • ArgumentNullException:如果数组为null。
  • ArgumentOutOfRangeException:如果索引小于零。
  • InvalidCastException:如果无法将源Hashtable的类型强制转换为目标数组的类型。
  • ArgumentException:如果array是多维的,或者源Hashtable中的元素数大于从arrayIndex到目标数组末尾的可用空间。

下面的程序说明了Hashtable.CopyTo(Array,Int32)方法的用法:

范例1:

// C# code to copy the Hashtable
// elemets to a one-dimensional Array
// instance at the specified index.
using System;
using System.Collections;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a Hashtable named myhash
        Hashtable myhash = new Hashtable();
  
        // Adding key/value pairs in myhash
        myhash.Add("A", "Apple");
        myhash.Add("B", "Banana");
        myhash.Add("C", "Cat");
        myhash.Add("D", "Dog");
        myhash.Add("E", "Elephant");
        myhash.Add("F", "Fish");
  
        // Creating a one-dimensional Array named myArr
        DictionaryEntry[] myArr = new DictionaryEntry[myhash.Count];
  
        // copying the Hashtable entries
        // to a one-dimensional Array instance
        // at the specified index
        myhash.CopyTo(myArr, 0);
  
        for (int i = 0; i < myArr.Length; i++)
            Console.WriteLine(myArr[i].Key + " --> "
                              + myArr[i].Value);
    }
}

输出:

B --> Banana
C --> Cat
A --> Apple
F --> Fish
D --> Dog
E --> Elephant

范例2:

// C# code to copy the Hashtable
// elemets to a one-dimensional Array
// instance at the specified index.
using System;
using System.Collections;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a Hashtable named myhash
        Hashtable myhash = new Hashtable();
  
        // Adding key/value pairs in myhash
        myhash.Add("A", "Apple");
        myhash.Add("B", "Banana");
        myhash.Add("C", "Cat");
        myhash.Add("D", "Dog");
        myhash.Add("E", "Elephant");
        myhash.Add("F", "Fish");
  
        // Creating a one-dimensional Array named myArr
        DictionaryEntry[] myArr = new DictionaryEntry[myhash.Count];
  
        // copying the HybridDictionary entries
        // to a one-dimensional Array instance
        // at the specified index
        // This should raise "ArgumentOutOfRangeException"
        // as index is less than 0
        myhash.CopyTo(myArr, -2);
  
        for (int i = 0; i < myArr.Length; i++)
            Console.WriteLine(myArr[i].Key + " --> "
                              + myArr[i].Value);
    }
}

运行时错误:

笔记:

  • 元素将以枚举器遍历Hashtable的相同顺序复制到Array中。
  • 要仅复制哈希表中的键,请使用Hashtable.Keys.CopyTo
  • 要仅复制Hashtable中的值,请使用Hashtable.Values.CopyTo
  • 此方法是O(n)运算,其中n是Count。

参考:

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