我在内存中有一个字节数组,从文件中读取.我想在某个点(索引)拆分字节数组,而不必只创建一个新的字节数组并一次复制每个字节,从而增加了操作的内存占用量.我想要的是这样的:
byte[] largeBytes = [1,2,3,4,5,6,7,8,9]; byte[] smallPortion; smallPortion = split(largeBytes, 3);
smallPortion
将等于1,2,3,4
largeBytes
将等于5,6,7,8,9
仅供参考. System.ArraySegment
结构基本上与ArrayView
上面代码中的相同.如果您愿意,可以以相同的方式使用这种开箱即用的结构.
在使用Linq的C#中,您可以这样做:
smallPortion = largeBytes.Take(4).ToArray(); largeBytes = largeBytes.Skip(4).Take(5).ToArray();
;)
我就是这样做的:
using System; using System.Collections; using System.Collections.Generic; class ArrayView: IEnumerable { private readonly T[] array; private readonly int offset, count; public ArrayView(T[] array, int offset, int count) { this.array = array; this.offset = offset; this.count = count; } public int Length { get { return count; } } public T this[int index] { get { if (index < 0 || index >= this.count) throw new IndexOutOfRangeException(); else return this.array[offset + index]; } set { if (index < 0 || index >= this.count) throw new IndexOutOfRangeException(); else this.array[offset + index] = value; } } public IEnumerator GetEnumerator() { for (int i = offset; i < offset + count; i++) yield return array[i]; } IEnumerator IEnumerable.GetEnumerator() { IEnumerator enumerator = this.GetEnumerator(); while (enumerator.MoveNext()) { yield return enumerator.Current; } } } class Program { static void Main(string[] args) { byte[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; ArrayView p1 = new ArrayView (arr, 0, 5); ArrayView p2 = new ArrayView (arr, 5, 5); Console.WriteLine("First array:"); foreach (byte b in p1) { Console.Write(b); } Console.Write("\n"); Console.WriteLine("Second array:"); foreach (byte b in p2) { Console.Write(b); } Console.ReadKey(); } }