System.Array는 ICloneable, IList, ICollection 및 IEnumerable 등과 같은 인터페이스를 구현합니다. ICloneable 인터페이스는 기존 개체, 즉 복제본의 복사본을 만듭니다.
ICloneable 인터페이스에 대해 알아보겠습니다. 현재 인스턴스의 복사본인 새 개체를 생성하기 때문에 Clone() 메서드만 있습니다.
다음은 ICloneable 인터페이스를 사용하여 복제를 수행하는 방법을 보여주는 예입니다 -
예시
using System;
class Car : ICloneable {
int width;
public Car(int width) {
this.width = width;
}
public object Clone() {
return new Car(this.width);
}
public override string ToString() {
return string.Format("Width of car = {0}",this.width);
}
}
class Program {
static void Main() {
Car carOne = new Car(1695);
Car carTwo = carOne.Clone() as Car;
Console.WriteLine("{0}mm", carOne);
Console.WriteLine("{0}mm", carTwo);
}
} 이제 C#에서 Array.Clone을 사용하여 배열을 복제하는 방법을 살펴보겠습니다. −
예시
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));
// cloned array
Console.WriteLine(string.Join(",", arrCloned));
Console.WriteLine();
}
}