【问题标题】:C# sub-array without memory allocations (copying) [duplicate]没有内存分配的 C# 子数组(复制)[重复]
【发布时间】:2016-12-28 10:25:00
【问题描述】:

在 C# 中是否可以在现有数组之上创建临时子数组而无需内存分配/复制?

【问题讨论】:

    标签: c# arrays


    【解决方案1】:

    您可以使用ArraySegment 结构:

    分隔一维数组的一部分。

    也看看这个问题:what is the use of ArraySegment class?

    这是从斯蒂芬肯尼迪的答案中窃取的示例用法:

    var array = new byte[] { 5, 8, 9, 20, 70, 44, 2, 4 };
    array.Dump();
    var segment = new ArraySegment<byte>(array, 2, 3);
    segment.Dump(); // output: 9, 20, 70
    segment.Reverse().Dump(); // output 70, 20, 9
    segment.Any(s => s == 99).Dump(); // output false
    segment.First().Dump(); // output 9
    array.Dump(); // no change
    

    【讨论】:

    • new ArraySegment 已经是一个分配动作
    猜你喜欢
    • 2012-03-24
    • 2012-12-13
    • 1970-01-01
    • 2020-01-31
    • 2012-12-23
    • 2011-06-23
    • 2018-09-06
    • 2014-07-11
    • 2021-12-08
    相关资源
    最近更新 更多