IntPtr.Addition(IntPtr, Int32) 運算子

定義

將位移加入帶正負號的整數。

public:
 static IntPtr operator +(IntPtr pointer, int offset);
public static IntPtr operator + (IntPtr pointer, int offset);
static member ( + ) : nativeint * int -> nativeint
Public Shared Operator + (pointer As IntPtr, offset As Integer) As IntPtr

參數

pointer
IntPtr

nativeint

要加入位移的帶正負號整數。

offset
Int32

要加上的位移。

傳回

IntPtr

nativeint

新的帶正負號的整數,反映 offset 新增至 pointer 的 。

備註

方法 Addition 會定義 物件的加法 IntPtr 運算。 它會啟用下列程式碼。

int[] arr = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };
unsafe {
   fixed(int* parr = arr)
   {
       IntPtr ptr = new IntPtr(parr);
       for (int ctr = 0; ctr < arr.Length; ctr++)
       {
          IntPtr newPtr = ptr + ctr * sizeof(Int32);
          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.Runtime.InteropServices
open FSharp.NativeInterop

[<EntryPoint>]
let main _ =
    let arr =
        [| 2; 4; 6; 8; 10; 12; 14; 16; 18; 20 |]
        
    use parr = fixed arr

    let ptr = NativePtr.toNativeInt parr

    for i = 0 to arr.Length - 1 do
        let newPtr = ptr + nativeint i * nativeint sizeof<int>
        printf $"{Marshal.ReadInt32 newPtr}   "
    0

    // The example displays the following output:
    //       2   4   6   8   10   12   14   16   18   20
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 = ptr + ctr * Len(arr(0))
   Console.WriteLine("{0}   ", Marshal.ReadInt32(newPtr))
Next
' The example displays the following output:
'       2   4   6   8   10   12   14   16   18   20

不支援自訂運算子的語言可以改為呼叫 Add 方法。

如果結果太大而無法在執行中以帶正負號的整數表示,則加法運算不會擲回例外狀況。 相反地,它會在未核取的內容中執行。

從 11 版開始,在以 .NET 7 或更新版本執行時間為目標的 C# 中,此 API 只能透過反映來存取。 加法運算子會由語言直接辨識,而且會遵循加法運算的一般語言行為,包括如果結果太大而無法表示,內容中 checked 就會溢位。

這個運算子的對等方法為 IntPtr.Add(IntPtr, Int32)

適用於

另請參閱