众所周知,Array 一旦定义好,譬如四个长度,当需要再往里面添加元素的时候,需要Array.Resize一下才可以,为了提高代码复用,所以索性封装下,方便使用,代码如下:
class="csharpcode"> /// <summary> /// Array添加 /// </summary> /// <typeparam name="T">泛型</typeparam> /// <param name="array">Array</param> /// <param name="item">需要添加项</param> /// <returns>返回新的Array</returns> public static T[] Add<T>(this T[] array, T item) { int _count = array.Length; Array.Resize<T>(ref array, _count + 1); array[_count] = item; return array; } /// <summary> /// Array添加 /// </summary> /// <typeparam name="T">泛型</typeparam> /// <param name="sourceArray">Array</param> /// <param name="addArray">Array</param> /// <returns>返回新的Array</returns> public static T[] AddRange<T>(this T[] sourceArray, T[] addArray) { int _count = sourceArray.Length; int _addCount = addArray.Length; Array.Resize<T>(ref sourceArray, _count + _addCount); //foreach (T t in addArray) //{ // sourceArray[_count] = t; // _count++; //} addArray.CopyTo(sourceArray, _count); return sourceArray; }
测试代码:
[TestMethod()] public void AddTest() { int[] _source = new int[3] { 1, 2, 3 }; int[] _expected = new int[4] { 1, 2, 3, 4 }; _source = _source.Add(4); CollectionAssert.AreEqual(_source, _expected); } [TestMethod()] public void AddRangeTest() { int[] _source = new int[3] { 1, 2, 3 }; int[] _expected = new int[6] { 1, 2, 3, 4, 5, 6 }; _source = _source.AddRange(new int[3] { 4, 5, 6 }); CollectionAssert.AreEqual(_source, _expected); }
测试结果:
代码逻辑很简单,无需说明,只是方面后续使用而已,这是基于.NET 2.0的写法,大家都知道,在.NET 3.0+有了LINQ出现,实现此效果更为简单方面,代码如下:
/// <summary> /// Array添加 /// </summary> /// <typeparam name="T">泛型</typeparam> /// <param name="array">Array</param> /// <param name="item">需要添加项</param> /// <returns>返回新的Array</returns> public static T[] Add<T>(this T[] array, T item) { array =
array.Concat
<T>(new T[1] { item }).ToArray(); return array; } /// <summary> /// Array添加 /// </summary> /// <typeparam name="T">泛型</typeparam> /// <param name="sourceArray">Array</param> /// <param name="addArray">Array</param> /// <returns>返回新的Array</returns> public static T[] AddRange<T>(this T[] sourceArray, T[] addArray) { sourceArray =
sourceArray.Concat
<T>(addArray).ToArray();
return sourceArray;
}
同样的测试代码:
[TestMethod()] public void AddTest() { int[] _source = new int[3] { 1, 2, 3 }; int[] _expected = new int[4] { 1, 2, 3, 4 }; _source = _source.Add(4); CollectionAssert.AreEqual(_source, _expected); } [TestMethod()] public void AddRangeTest() { int[] _source = new int[3] { 1, 2, 3 }; int[] _expected = new int[6] { 1, 2, 3, 4, 5, 6 }; _source = _source.AddRange(new int[3] { 4, 5, 6 }); CollectionAssert.AreEqual(_source, _expected); }
测试结果:
希望有所帮助!