IntPtr.Subtraction(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

新的指標,其可反映從 pointer 減去 offset 的結果。

備註

方法 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 方法。

如果結果太小而無法表示為指定平臺上的指標,減法運算就不會擲回例外狀況。 相反地,它會在未核取的內容中執行。

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

適用於

另請參閱