有什么办法来创建一个跨 或内存 其指的是列表中的元素 在C#中?

问题描述 投票:4回答:1

很显然,我可以(首先转换到一个数组为例)来间接的,但我的目标,以避免尽可能多的拷贝和分配成为可能。最后,我想编写一个返回Memory<T>和从List<T>内部对象构造函数。

c#
1个回答
3
投票

只要你保证不改变存储器操作之间.Count的价值,从来没有这样做将导致列表的内部数组被换出以下将工作的任何行动。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace SandboxNetStandard
{
    public static class ListAdapter<T>
    {
        private static readonly FieldInfo _arrayField = typeof(List<T>)
            .GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
            .Single(x => x.FieldType == typeof(T[]));

        /// <summary>
        /// Converts
        /// <paramref name="listIPromiseToNotChangeTheCountOfAndNotCauseCapacityToChange"/>
        /// to an <see cref="Memory{T}"/>.
        /// </summary>
        /// <param name="listIPromiseToNotChangeTheCountOfAndNotCauseCapacityToChange">
        /// The list to convert.
        ///
        /// On each use of the returned memory object the list must have the same value of
        /// <see cref="List{T}.Count"/> as the original passed in value. Also between calls 
        /// you must not do any action that would cause the internal array of the list to
        /// be swapped out with another array.
        /// </param>
        /// <returns>
        /// A <see cref="Memory{T}"/> that is linked to the passed in list.
        /// </returns>
        public static Memory<T> ToMemory(
            List<T> listIPromiseToNotChangeTheCountOfAndNotCauseCapacityToChange)
        {
            Memory<T> fullArray = (T[]) _arrayField.GetValue(
                    listIPromiseToNotChangeTheCountOfAndNotCauseCapacityToChange);
            return fullArray.Slice(0,
                listIPromiseToNotChangeTheCountOfAndNotCauseCapacityToChange.Count);
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.