如何获得无子的克隆数组 [英] How to get sub array without cloning
问题描述
我知道在C#中,我们总是可以通过使用 Array.Copy()
方法获取给定数组的子数组。然而,这将消耗更多的存储器和处理时间,这是在只读情况是不必要的。例如,我正在写在集群中与其他节点交换信息非常频繁重负载的网络程序。前20个字节的每封邮件的是邮件标题,其余的字节组成了邮件正文。因此,我会以单独处理它们划分接收到的原始信息为标题字节数组,身体字节数组。但是,这显然会消耗双倍的内存和额外的时间。在C中,我们可以很容易地使用指针和偏移分配给它访问数组的不同部分。
例如,在C语言中,如果我们有一个的char a [] =ABCDEFGHIJKLMN
,我们可以声明一个的char * PTR = A + 3
来表示数组 DEFGHIJKLMN
。
I know in C# we can always get the sub-array of a given array by using Array.Copy()
method. However, this will consume more memory and processing time which is unnecessary in read-only situation. For example, I'm writing a heavy load network program which exchanges messages with other nodes in the cluster very frequently. The first 20 bytes of every message is the message header while the rest bytes make up the message body. Therefore, I will divide the received raw message into header byte array and body byte array in order to process them separately. However, this will obviously consume double memory and extra time. In C, we can easily use a pointer and assign offset to it to access different parts of the array.
For instance, in C language, if we have a char a[] = "ABCDEFGHIJKLMN"
, we can declare a char* ptr = a + 3
to represent the array DEFGHIJKLMN
.
有没有办法来在C#中做到这一点?
Is there a way to accomplish this in C#?
推荐答案
您可能会感兴趣的 ArraySegments
或的 不安全
You might be interested in ArraySegments
or unsafe
.
ArraySegments
划定一个一维数组的一部分。
ArraySegments
delimits a section of a one-dimensional array.
ArraySegments使用例子:
ArraySegments usage example:
int[] array = { 10, 20, 30 };
ArraySegment<int> segment = new ArraySegment<int>(array, 1, 2);
// The segment contains offset = 1, count = 2 and range = { 20, 30 }
不安全
定义一个不安全的环境中,指针可以使用。
Unsafe
define an unsafe context in which pointers can be used.
不安全使用例子:
int[] a = { 4, 5, 6, 7, 8 };
unsafe
{
fixed (int* c = a)
{
// use the pointer
}
}
这篇关于如何获得无子的克隆数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!