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)); //克隆数组 Console.WriteLine(string.Join(",", arrCloned)); Console.WriteLine(); } }