C#完成Array添加擴大實例。本站提示廣大學習愛好者:(C#完成Array添加擴大實例)文章只能為提供參考,不一定能成為您想要的結果。以下是C#完成Array添加擴大實例正文
普通學過C#的都曉得,Array 一旦界說好,好比四個長度,當須要再往外面添加元素的時刻,須要Array.Resize一下才可以。有鑒於此,為了進步代碼復用,所以索性封裝下,便利應用。
詳細完成代碼以下:
/// <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); }
測試成果:
願望本文能對年夜家有所贊助!