共用方式為


IntPtr.Subtract(IntPtr, Int32) 方法

定義

從帶正負號的整數減去位移。

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

參數

pointer
IntPtr

nativeint

要減去位移的帶正負號整數。

offset
Int32

要減去的位移。

傳回

IntPtr

nativeint

反映 減 pointer 法的新帶正負號 offset 整數。

範例

下列範例會具現化 IntPtr 指向十個元素陣列結尾的物件,然後呼叫 Subtract 方法,以反向順序逐一查看陣列中的專案。

using System;
using System.Runtime.InteropServices;

public class Example
{
   public static void Main()
   {
      int[] arr = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
      // Get the size of a single array element.
      int size = sizeof(int);
      unsafe {
         fixed(int* pend = &arr[arr.GetUpperBound(0)]) {
            IntPtr ptr = new IntPtr(pend);
            for (int ctr = 0; ctr < arr.Length; ctr++)
            {
               IntPtr newPtr = IntPtr.Subtract(ptr, ctr * size);
               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
open System.Runtime.InteropServices
open FSharp.NativeInterop

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

    // Get the size of a single array element.
    let size = sizeof<int>

    use pend = fixed &arr[arr.GetUpperBound 0]
    let ptr = NativePtr.toNativeInt pend 
    for i = 0 to arr.Length - 1 do
        let newPtr = IntPtr.Subtract(ptr, i * size)
        printf $"{Marshal.ReadInt32 newPtr}   "
    0

// The example displays the following output:
//       20   18   16   14   12   10   8   6   4   2
Imports System.Runtime.InteropServices

Module Example
   Public Sub Main()
      Dim arr() As Integer = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20}
      Dim ptr As IntPtr = Marshal.UnsafeAddrOfPinnedArrayElement(arr, arr.Length - 1)
      Dim size As Integer = Len(arr(0))

      For ctr As Integer = 0 To arr.Length - 1
         Dim newPtr As IntPtr = IntPtr.Subtract(ptr, ctr * size)
         Console.Write("{0}   ", Marshal.ReadInt32(newPtr))
      Next
   End Sub
End Module
' The example displays the following output:
'       20   18   16   14   12   10   8   6   4   2

備註

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

不支援運算子多載或自訂運算子的語言,可以使用這個方法從指標的值減去位移。

適用於

另請參閱