gpt4 book ai didi

c# - 有什么方法可以在 C# 中创建引用 List 元素的 Span 或 Memory 吗?

转载 作者:太空狗 更新时间:2023-10-30 01:29:04 26 4
gpt4 key购买 nike

显然我可以间接这样做(例如首先转换为数组),但我的目标是尽可能避免复制和分配。最终,我想编写一个返回 Memory<T> 的函数。并从 List<T> 内部构造该对象.

最佳答案

只要您保证在对内存的操作之间不更改 .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);
}
}
}

关于c# - 有什么方法可以在 C# 中创建引用 List<T> 元素的 Span<T> 或 Memory<T> 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54508054/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com