Computer >> Máy Tính >  >> Lập trình >> C#

Giao diện ICloneable làm được gì trong C #?

Giao diện ICloneable tạo ra một bản sao của đối tượng hiện tại, tức là một bản sao.

Nó chỉ có một phương pháp duy nhất -

  • Bản sao () - Phương thức clone () tạo một đối tượng mới là bản sao của phiên bản hiện tại.

Sau đây là một ví dụ cho thấy cách thực hiện sao chép bằ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);
   }
}

Đầu ra

Width of car = 1695mm
Width of car = 1695mm