c# – 为什么ImmutableArray.Create复制一个现有的不可变数组?
我试图制作一个现有的ImmutableArray< T>在一个方法和思想中,我可以使用构造方法Create< T>(ImmutableArray< T> a,int offset,int count),如下所示:
var arr = ImmutableArray.Create('A','B','C','D'); var bc ImmutableArray.Create(arr,1,2); 我希望我的两个ImmutableArrays可以在这里共享底层数组.但 从2017年3月18日的15757a8开始 /// <summary> /// Initializes a new instance of the <see cref="ImmutableArray{T}"/> struct. /// </summary> /// <param name="items">The array to initialize the array with. /// The selected array segment may be copied into a new array.</param> /// <param name="start">The index of the first element in the source array to include in the resulting array.</param> /// <param name="length">The number of elements from the source array to include in the resulting array.</param> /// <remarks> /// This overload allows helper methods or custom builder classes to efficiently avoid paying a redundant /// tax for copying an array when the new array is a segment of an existing array. /// </remarks> [Pure] public static ImmutableArray<T> Create<T>(ImmutableArray<T> items,int start,int length) { Requires.Range(start >= 0 && start <= items.Length,nameof(start)); Requires.Range(length >= 0 && start + length <= items.Length,nameof(length)); if (length == 0) { return Create<T>(); } if (start == 0 && length == items.Length) { return items; } var array = new T[length]; Array.Copy(items.array,start,array,length); return new ImmutableArray<T>(array); } 为什么必须在这里制作基础项目的副本?
但是,分段情况正好在它复制时,如果所需的切片为空或整个输入数组,它只会避免复制. 有没有另一种方法可以实现我想要的东西,而不是实现某种ImmutableArraySpan? 解决方法
我将借助评论回答我自己的问题:
ImmutableArray不能表示底层数组的一个片段,因为它没有相应的字段 – 显然添加64/128位只很少使用的范围字段会太浪费. 所以唯一的可能性就是拥有一个合适的Slice / Span结构,除了ArraySegment(它不能使用ImmutableArray作为后备数据)之外,目前还没有一个结构. 编写实现IReadOnlyList< T>的ImmutableArraySegment可能很容易.所以这可能是解决方案. 关于文档 – 它尽可能正确,它避免了它可以(所有,没有)和副本的少数副本. 新的Span和ReadonlySpan类型都有新的API,它们将附带低级代码(ref return / locals)的神奇语言和运行时功能.这些类型实际上已作为System.Memory nuget包的一部分提供,但直到它们是集成的,将无法使用它们来解决在ImmutableArray上切片ImmutableArray的问题,而ImmutableArray需要这个方法(在System.Collections.Immutable中,它不依赖于System.Memory类型) public ReadonlySpan<T> Slice(int start,int count) 我猜/希望这些API一旦到位就会出现. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |