|
示例
using System;class Test{ static void WriteLocations(byte[] arr) { unsafe { fixed (byte* pArray = arr) { byte* pElem = pArray; for (int i = 0; i < arr.Length; i++) { byte value = *pElem; Console.WriteLine("arr[{0}] at 0x{1:X} is {2}", i, (uint)pElem, value); pElem++; } } } } static void Main() { byte[] arr = new byte[] {1, 2, 3, 4, 5}; WriteLocations(arr); }} 显示了一个名为 WriteLocations 的方法。它含有一个不安全块,该块固定了一个数组实例,然后使用指针操作实现逐个地访问该数组的元素。每个数组元素的索引、值和位置被写入控制台。下面是一个可能的输出示例:
arr[0] at 0x8E0360 is 1arr[1] at 0x8E0361 is 2arr[2] at 0x8E0362 is 3arr[3] at 0x8E0363 is 4arr[4] at 0x8E0364 is 5 当然,确切的内存位置可能因应用程序的不同执行而异。
|