IntPtr.Addition(IntPtr, Int32) 運算子
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
將位移加入帶正負號的整數。
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 方法。
如果結果太大無法在執行過程中以有符號整數表示,加法運算不會拋出例外。 相反地,它在一個不受限制的情境中進行。
在 C# 從版本 11 開始,且針對 .NET 7 或更新執行環境時,此 API 僅能透過反射存取。 加法運算子會被語言直接識別,並遵循加法運算的正常語言行為,包括當結果過大無法表示時,會在上下文中溢 checked 出。
此運算子的等價方法為 IntPtr.Add(IntPtr, Int32)