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

การโคลน (Cloning) อาร์เรย์ใน C#

การโคลนใน C# มีประโยชน์หากต้องการสร้างสำเนาของอาร์เรย์ เมธอด Clone() ใช้สร้างสำเนาที่คล้ายกัน C# มีทั้งเมธอด Clone และอินเทอร์เฟซ ICloneable

ตัวอย่าง

using System;

class Program {
    static void Main() {
        string[] arr = { "one", "two", "three", "four", "five" };
        string[] arrCloned = arr.Clone() as string[];
        Console.WriteLine(string.Join(",", arr));
        Console.WriteLine(string.Join(",", arrCloned));
        Console.WriteLine();
    }
}

ผลลัพธ์

one,two,three,four,five
one,two,three,four,five

อธิบาย: ใช้ arr.Clone() as string[] เพื่อโคลนอาร์เรย์สตริง