IntPtr.Add(IntPtr, Int32) 方法  
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
向带符号整数添加偏移量。
public:
 static IntPtr Add(IntPtr pointer, int offset);public static IntPtr Add (IntPtr pointer, int offset);static member Add : nativeint * int -> nativeintPublic Shared Function Add (pointer As IntPtr, offset As Integer) As IntPtr参数
- pointer
- 
				
				IntPtr
nativeint 
要向其添加偏移量的带符号整数。
- offset
- Int32
要增加的偏移量。
返回
- 
			
			IntPtr
nativeint 
一个新的有符号整数,反映 offset 添加到 pointer的符号整数。
示例
下面的示例实例化一个 IntPtr 指向十个元素数组开头的对象,然后调用 Add 该方法来循环访问数组中的元素。
using System;
using System.Runtime.InteropServices;
public class Example
{
   public static void Main()
   {
      int[] arr = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };
      unsafe {
         fixed(int* parr = arr) {
            IntPtr ptr = new IntPtr(parr);
            // Get the size of an array element.
            int size = sizeof(int);
            for (int ctr = 0; ctr < arr.Length; ctr++)
            {
               IntPtr newPtr = IntPtr.Add(ptr, ctr * size);
               Console.Write("{0}   ", Marshal.ReadInt32(newPtr));
            }
         }
      }
   }
}
// The example displays the following output:
//       2   4   6   8   10   12   14   16   18   20
#nowarn "9"
open System
open System.Runtime.InteropServices
open FSharp.NativeInterop
[<EntryPoint>]
let main _ =
    let mutable arr = 
        [| 2; 4; 6; 8; 10; 12; 14; 16; 18; 20 |]
    
    use parr = fixed arr
    
    let ptr = NativePtr.toNativeInt parr
    // Get the size of an array element.
    let size = sizeof<int>
    for i = 0 to arr.Length - 1 do
        let newPtr = IntPtr.Add(ptr, i * size)
        printf $"{Marshal.ReadInt32 newPtr}   "
    0
// The example displays the following output:
//       2   4   6   8   10   12   14   16   18   20
Imports System.Runtime.InteropServices
Module Example
   Public Sub Main()
      Dim arr() As Integer = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 }
      Dim ptr As IntPtr = Marshal.UnsafeAddrOfPinnedArrayElement(arr, 0)
      For ctr As Integer= 0 To arr.Length - 1
         Dim newPtr As IntPtr = IntPtr.Add(ptr, ctr * Len(arr(0)))
         Console.Write("{0}   ", Marshal.ReadInt32(newPtr))
      Next
   End Sub
End Module
' The example displays the following output:
'       2   4   6   8   10   12   14   16   18   20
注解
如果结果太大,无法表示为执行过程中的有符号整数,则 Add 该方法不会引发异常。 相反,添加操作是在未选中的上下文中执行的。
不支持运算符重载或自定义运算符的语言可以使用此方法向指针值添加偏移量。