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); }
为什么必须在这里制作基础项目的副本?
并不是这种方法的文档误导/错误?它说
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.
但是,分段情况正好在它复制时,如果所需的切片为空或整个输入数组,它只会避免复制.
有没有另一种方法可以实现我想要的东西,而不是实现某种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一旦到位就会出现.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。