Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C# Array 클래스가 구현하는 인터페이스 완벽 정리

System.Array 클래스는 ICloneable, IList, ICollection, IEnumerable 등 다양한 인터페이스를 구현하고 있습니다. 그중 ICloneable 인터페이스는 기존 객체의 복사본, 즉 클론(clone)을 생성하는 역할을 담당합니다.

ICloneable 인터페이스란?

ICloneable 인터페이스에는 Clone() 메서드 하나만 정의되어 있습니다. 이 메서드는 현재 인스턴스의 복사본인 새로운 객체를 생성해 반환합니다.

다음 예제는 ICloneable 인터페이스를 사용해 객체를 복제하는 방법을 보여줍니다.

예제 1: 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() 메서드를 활용해 배열 자체를 복제하는 방법을 살펴보겠습니다.

예제 2: 배열 복제하기

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();
    }
}

정리

System.Array는 ICloneable, IList, ICollection, IEnumerable 인터페이스를 구현하며, Clone() 메서드를 호출하면 배열의 얕은 복사본(shallow copy)인 새로운 배열 객체를 손쉽게 만들 수 있습니다. 단, 복제된 배열의 요소는 원본과 동일한 객체를 참조한다는 점을 기억해 두면 좋습니다.