在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(); } }
廣告