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 开始的 C# 中,以 .NET 7 或更高版本运行时为目标时,只能通过反射访问此 API。 减法运算符由语言直接识别,并将遵循减法运算的正常语言行为,包括在结果太小而无法表示时在上下文中 checked 溢出。

此运算符的等效方法是 IntPtr.Subtract(IntPtr, Int32)

适用于

另请参阅