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

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

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

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

適用於

另請參閱