Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

Array Copy ใน C#

ใช้ Array.Copy() คัดลอกส่วนของอาร์เรย์ไปยังอีกอาร์เรย์หนึ่ง

Syntax

Array.Copy(sourceArray, sourceIndex, destArray, destIndex, length);
  • sourceArray - อาร์เรย์ต้นทาง
  • sourceIndex - เริ่มต้นที่ Index นี้ในต้นทาง
  • destArray - อาร์เรย์ปลายทาง
  • destIndex - เริ่มต้นที่ Index นี้ในปลายทาง
  • length - จำนวนสมาชิกที่จะคัดลอก

ตัวอย่างโค้ดเต็ม

using System;
namespace ArrayApplication {
    class MyArray {
        static void Main(string[] args) {
            int[] src = new int[10]; // 10 elements
            int[] dest = new int[5]; // 5 elements
            // กำหนดค่า Source: 100, 101, 102...
            for (int i = 0; i < 10; i++) src[i] = i + 100;
            Console.WriteLine("Original Array:");
            foreach (int v in src) Console.Write(v + " "); // 100 101 ... 109
            // คัดลอก 5 ตัวแรกจาก src ไป dest
            Array.Copy(src, 0, dest, 0, 5);
            Console.WriteLine("\nNew Array (copied):");
            foreach (int v in dest) Console.Write(v + " "); // 100 101 102 103 104
            Console.ReadKey();
        }
    }
}

ผลลัพธ์

Original Array: 100 101 102 103 104 105 106 107 108 109
New Array (copied): 100 101 102 103 104

เมธอดที่เกี่ยวข้อง

  • Array.ConstrainedCopy - คัดลอกแบบ Atomic (ทั้งหมดหรือไม่เลย)
  • Buffer.BlockCopy - คัดลอกระดับ Byte (เร็วกว่าสำหรับ Primitive types)
  • List<T>.GetRange / ToArray - สำหรับ List
  • Span<T> / Memory<T> - Zero-copy slicing (Modern .NET)