IntPtr.Subtraction(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減法。
備註
此 Subtraction 方法定義了物件的 IntPtr 減法運算。 它能啟用以下程式碼。
int[] arr = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
unsafe {
fixed(int* parr = &arr[arr.GetUpperBound(0)])
{
IntPtr ptr = new IntPtr(parr);
for (int ctr = 0; ctr <= arr.GetUpperBound(0); ctr++)
{
IntPtr newPtr = ptr - ctr * sizeof(Int32);
Console.Write("{0} ", Marshal.ReadInt32(newPtr));
}
}
}
// The example displays the following output:
// 20 18 16 14 12 10 8 6 4 2
#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[arr.GetUpperBound 0]
let ptr = NativePtr.toNativeInt parr
for i = 0 to arr.GetUpperBound 0 do
let newPtr = ptr - nativeint i * nativeint sizeof<int>
printf $"{Marshal.ReadInt32 newPtr} "
0
// The example displays the following output:
// 20 18 16 14 12 10 8 6 4 2
Dim arr() As Integer = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20 }
Dim ptr As IntPtr = Marshal.UnsafeAddrOfPinnedArrayElement(arr, arr.GetUpperBound(0))
For ctr As Integer= 0 To arr.GetUpperBound(0)
Dim newPtr As IntPtr = ptr - ctr * Len(arr(0))
Console.Write("{0} ", Marshal.ReadInt32(newPtr))
Next
不支援自訂運算子的語言則可直接呼叫該 Subtract 方法。
若結果過小無法在執行過程中以有符號整數表示,減法運算不會拋出例外。 相反地,它在一個不受限制的情境中進行。
在 C# 從版本 11 開始,且針對 .NET 7 或更新執行環境時,此 API 僅能透過反射存取。 減法運算子會被語言直接識別,並遵循減法運算的正常語言行為,包括如果結果太小無法表示,則會在上下文中溢 checked 出。
此運算子的等價方法為 IntPtr.Subtract(IntPtr, Int32)