Прочитать на английском

Поделиться через


Hashtable.CopyTo(Array, Int32) Метод

Определение

Копирует элементы коллекции Hashtable в экземпляр класса одномерного массива Array по указанному индексу.

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

Параметры

array
Array

Одномерный массив Array, который является назначением для объектов DictionaryEntry, копируемых из коллекции Hashtable. Массив Array должен иметь индексацию, начинающуюся с нуля.

arrayIndex
Int32

Отсчитываемый от нуля индекс в массиве array, указывающий начало копирования.

Реализации

Исключения

array имеет значение null.

Значение параметра arrayIndex меньше нуля.

Массив array является многомерным.

-или-

Число элементов в исходной коллекции Hashtable больше доступного места от положения, заданного значением параметра arrayIndex, до конца массива назначения array.

Тип исходного массива Hashtable не может быть автоматически приведен к типу массива назначения array.

Примеры

В следующем примере показано, как скопировать список ключей или список значений в Hashtable одномерном Arrayобъекте .

using System;
using System.Collections;
public class SamplesHashtable
{

   public static void Main()
   {
      // Creates and initializes the source Hashtable.
      var mySourceHT = new Hashtable();
      mySourceHT.Add("A", "valueA");
      mySourceHT.Add("B", "valueB");

      // Creates and initializes the one-dimensional target Array.
      var myTargetArray = new String[15];
      myTargetArray[0] = "The";
      myTargetArray[1] = "quick";
      myTargetArray[2] = "brown";
      myTargetArray[3] = "fox";
      myTargetArray[4] = "jumps";
      myTargetArray[5] = "over";
      myTargetArray[6] = "the";
      myTargetArray[7] = "lazy";
      myTargetArray[8] = "dog";

      // Displays the values of the target Array.
      Console.WriteLine("The target Array contains the following before:");
      PrintValues(myTargetArray, ' ');

      // Copies the keys in the source Hashtable to the target Hashtable, starting at index 6.
      Console.WriteLine("After copying the keys, starting at index 6:");
      mySourceHT.Keys.CopyTo(myTargetArray, 6);

      // Displays the values of the target Array.
      PrintValues(myTargetArray, ' ');

      // Copies the values in the source Hashtable to the target Hashtable, starting at index 6.
      Console.WriteLine("After copying the values, starting at index 6:");
      mySourceHT.Values.CopyTo(myTargetArray, 6);

      // Displays the values of the target Array.
      PrintValues(myTargetArray, ' ');
   }

   public static void PrintValues(String[] myArr, char mySeparator)
   {
      for (int i = 0; i < myArr.Length; i++)
         Console.Write($"{mySeparator}{myArr[i]}");
      Console.WriteLine();
   }
}
/*
This code produces the following output.

The target Array contains the following before:
 The quick brown fox jumps over the lazy dog
After copying the keys, starting at index 6:
 The quick brown fox jumps over B A dog
After copying the values, starting at index 6:
 The quick brown fox jumps over valueB valueA dog

*/

Комментарии

Элементы копируются в в Array том же порядке, в котором перечислитель выполняет итерацию по Hashtable.

Чтобы скопировать только ключи в , используйте HashtableHashtable.Keys.CopyTo.

Чтобы скопировать только значения в , используйте HashtableHashtable.Values.CopyTo.

Этот метод является операцией O(n) , где nCount.

Применяется к

Продукт Версии
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1
UWP 10.0

См. также раздел