Phương thức Clone() tạo bản sao nông (shallow copy) của mảng. Trả về object, cần ép kiểu.
Ví dụ
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)); // Original
Console.WriteLine(string.Join(",", arrCloned)); // Cloned
}
}
Kết quả
one,two,three,four,five
one,two,three,four,five
Lưu ý quan trọng:
- Shallow copy: Với mảng kiểu giá trị (int, struct...) → copy giá trị độc lập. Với mảng kiểu tham chiếu (class, string...) → copy tham chiếu, cùng trỏ đến đối tượng gốc.
- Để deep copy: Duyệt và clone từng phần tử, hoặc serialize/deserialize.
ICloneableinterface cho phép class tự định nghĩa hành vi clone.