什麼是 C# 中 Array 類實現的介面?


System.Array 實現的介面包括 ICloneable、IList、ICollection、IEnumerable 等等。ICloneable 介面建立現有物件的副本,即克隆。

讓我們來了解 ICloneable 介面。它只有一個 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);
   }
}

現在讓我們看看如何在 C# 中使用 Array.Clone 來克隆一個數組 -

示例

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

      // cloned array
      Console.WriteLine(string.Join(",", arrCloned));
      Console.WriteLine();
   }
}

更新於: 2020 年 6 月 21 日

916 次瀏覽

開啟您的 職業

完成課程並獲得認證

開始
廣告
© . All rights reserved.