ICloneable 介面在 C# 中有什麼用?


ICloneable 介面建立現有物件的副本,即克隆。

它只有一個方法 −

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

輸出

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

更新日期:20-6 月-2020

2K+ 瀏覽次數

開啟您的 職業生涯

透過完成課程獲得認證

入門
廣告
© . All rights reserved.