Giao diện ICloneable tạo bản sao của đối tượng hiện có, tức là một bản clone.
Nó chỉ có một phương thức duy nhất:
Clone() - Phương thức clone() tạo đối tượng mới là bản sao của thể hiện hiện tại.
Dưới đây là ví dụ cho thấy cách thực hiện cloning sử dụng giao diện ICloneable:
Ví dụ
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);
}
}
Kết quả
Width of car = 1695mm Width of car = 1695mm