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);
    }

为什么必须在这里制作基础项目的副本?
并不是这种方法的文档误导/错误?它说

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一旦到位就会出现.

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...