c# - 创建对不同长度数组的新引用

标签 c# arrays

给定一些数组:

int[] array = new int[8000];

是否可以引用一个新数组:

int[] array2 = Array.SameReferenceDifferentLength(array, 4000);
// array1.Length == 8000;
// array2.Length == 4000;
// &array2[0] == &array[0];

最佳答案

使用ArraySegment结构:

var a = new string[] { "a", "b", "c", "d", "e" };

var b = new ArraySegment<string>(a, 1, 3);

foreach (var s in b)
{
    Console.WriteLine(s);
}

这对数组的指定范围进行浅引用。也就是说,它不会复制数组数据。

如果您想索引 ArraySegment<T> ,您可以将其转换为 IList<T>然后使用该接口(interface)提供的索引器。


模仿您问题中的代码:

int array = new int[8000];
var array2 = new ArraySegment<int>(array, 0, 4000);
//array.Length == 8000
//array2.Count == 4000
//array == array2.Array

关于c# - 创建对不同长度数组的新引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19193667/

相关文章:

c# - 如何在ListView中选择项目?

c# - BigInteger 不能表示无穷大

c# - Visual Studio 2015 : Unable to create universal application

c# - 项目添加到组合框时的事件

c# - DevOps nuget pack 步骤未拾取 dll

c - 当 argv*[] 是一个字符串时,如何通过 c 中的命令行传递数组?

c - 使用 Typedef 将元素存储在二维数组中

c# - 为什么这个 C# 函数的行为就像我在使用指针一样?

javascript - 使用 javascript 循环对象并将结果放入数组

arrays - Swift:通过函数更改全局变量的值。