在C#中,toArray是一个数组的方法,用于将集合转换为数组。但是有时候我们希望在不同的集合类型上使用toArray方法,这时候我们可以定义一个扩展方法来实现这个功能。
下面是一个示例代码,演示了如何定义一个扩展方法toArray,使其可以在不同的集合类型上使用:
using System;using System.Collections.Generic;public static class CollectionExtensions{ public static T[] toArray<T>(this ICollection<T> collection) { T[] array = new T[collection.Count]; collection.CopyTo(array, 0); return array; }}class Program{ static void Main() { List<int> list = new List<int> { 1, 2, 3, 4, 5 }; int[] array = list.toArray(); foreach (int num in array) { Console.WriteLine(num); } }}在上面的示例代码中,我们定义了一个扩展方法toArray,它接受一个ICollection
通过定义扩展方法toArray,我们可以在不同的集合类型上使用该方法,使代码更加灵活和可复用。


