C# 数组和指针
关于将数组传递给函数,然后操作数组内容(Array.Reverse),然后使用指针,我从数组中提取值。但在进入该函数之前,我要做的是:
byte[] arrayA = OriginalArray
byte[] arrayB = arrayA;
manipulate(OriginalArray);
抽象的函数看起来像这样
manipulateArray(byte[] OriginalArray) // This is unsafe
{
// Unsafe code that keeps a pointer to OriginalArray
// Array reverse
// Value extraction via pointer
}
这样做之后,令我惊讶的是,我得到的是 arrayB 现在“拥有”其值,就好像我已将其传递给函数一样!除非我错过了什么,否则我很确定我没有做错什么。我确保在 arrayA 和 arrayB 赋值之后调用该函数。
需要这方面的指导。 谢谢
Regarding passing arrays to functions and then manipulating the array contents (Array.Reverse) and then using pointers I extract the values from the array. But before jumping into the function, here is what I do;
byte[] arrayA = OriginalArray
byte[] arrayB = arrayA;
manipulate(OriginalArray);
And the function abstracted, looks like this
manipulateArray(byte[] OriginalArray) // This is unsafe
{
// Unsafe code that keeps a pointer to OriginalArray
// Array reverse
// Value extraction via pointer
}
After doing so, to my surprise what I am getting is that arrayB now "has" its values manipulated as if I had passed it to the function! Unless I missed something, I am pretty sure that I have not done something wrong. I made sure that the function is called after the arrayA and arrayB assignments.
Need guidance on this.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您希望 arrayB 保留相同的值,您需要复制 arrayA。在您的示例中, arrayA 和 arrayB 都指向相同的引用。
这是一个简单的例子来说明这一点:
If you want arrayB to retain the same values you'll need to make a copy of arrayA. Both arrayA and arrayB are pointing to the same reference in your example.
Here's a quick example to illustrate the point:
不会导致复制 arrayA,仅复制其引用 - 您正在将 arrayB 传递给该方法。
Does not cause copying of arrayA, only of its reference - you ARE passing arrayB to the method.
C# 中的数组是引用类型。 arrayA 和 arrayB 都只是对堆上同一个数组实例的引用(某种指针,但不是真正的指针)。如果您想提供副本,则必须显式
CopyTo()
数组内容。Arrays in C# are reference types. Both arrayA and arrayB are just references (sort-of pointers, but not really) to the same array instance on the heap. If you want to provide copies, you have to explicitly
CopyTo()
the array contents.