Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Các Interface được triển khai bởi lớp Array trong C#

System.Array triển khai các interface: ICloneable, IList, ICollection, IEnumerable, v.v. Interface ICloneable tạo bản sao đối tượng (clone).

ICloneable chỉ có phương thức Clone() để tạo đối tượng mới là bản sao của instance hiện tại.

Ví dụ: Clone đối tượng

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

Ví dụ: Clone mảng

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