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

更新於: 2020 年 6 月 20 日

已瀏覽 2K 次

啟動您的職業生涯

獲得課程認證

開始學習
廣告
© . All rights reserved.