什么是 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.