IntPtr.Zero 欄位

定義

唯讀欄位,表示已初始化為零的帶正負號整數。

public: static initonly IntPtr Zero;
public static readonly IntPtr Zero;
 staticval mutable Zero : nativeint
Public Shared ReadOnly Zero As IntPtr 

欄位值

IntPtr

nativeint

備註

這個欄位的值不等於 null 。 使用此欄位有效率地判斷 的 IntPtr 實例是否已設定為零以外的值。

例如,假設變數 ip 是 的 IntPtr 實例。 您可以藉由比較它與建構函式所傳回的值來判斷它是否已設定,例如:「 」 if ip != new IntPtr(0)... 。 不過,叫用建構函式以取得未初始化的指標沒有效率。 最好是撰寫 「 」 if ip != IntPtr.Zero... , 或 「 」 if !IntPtr.Zero.Equals(ip)...

從 Managed 程式碼呼叫 Windows API 時,如果引數必須是指標或 null ,則可以傳遞 IntPtr.Zero 而不是 null 。 例如,對 Windows CreateFile 函式的下列呼叫會 IntPtr.Zero 針對 pSecurityAttributeshTemplateFile 引數值提供 。

using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;

public class Example
{
   private const uint GENERIC_READ = 0x80000000;
   private const uint OPEN_EXISTING = 3;
   private const uint FILE_ATTRIBUTE_NORMAL = 128;
   private const uint FILE_FLAG_OVERLAPPED = 0x40000000;

   [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
   private static extern Microsoft.Win32.SafeHandles.SafeFileHandle CreateFile(
            string lpFileName, System.UInt32 dwDesiredAccess, System.UInt32 dwShareMode,
            IntPtr pSecurityAttributes, System.UInt32 dwCreationDisposition,
            System.UInt32 dwFlagsAndAttributes, IntPtr hTemplateFile);

   public static void Main()
   {
      SafeFileHandle hnd = CreateFile("CallOfTheWild.txt", GENERIC_READ, 0,
                                      IntPtr.Zero, OPEN_EXISTING,
                                      FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
                                      IntPtr.Zero);
      if (hnd.IsInvalid) {
            Exception ex = Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
            Console.WriteLine("Attempt to open file failed:");
            Console.WriteLine("  {0}", ex.Message);
            return;
      }
      else {
         Console.WriteLine("File successfully opened.");
         hnd.Close();
      }
   }
}
// If the file cannot be found, the example displays the following output:
//    Attempt to open file failed:
//      The system cannot find the file specified. (Exception from HRESULT: 0x80070002)
open Microsoft.Win32.SafeHandles
open System
open System.Runtime.InteropServices

let GENERIC_READ = 0x80000000u
let OPEN_EXISTING = 3u
let FILE_ATTRIBUTE_NORMAL = 128u
let FILE_FLAG_OVERLAPPED = 0x40000000u

[<DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)>]
extern SafeFileHandle CreateFile(
            string lpFileName, uint dwDesiredAccess, uint dwShareMode,
            nativeint pSecurityAttributes, uint dwCreationDisposition,
            uint dwFlagsAndAttributes, nativeint hTemplateFile)

let hnd = 
    CreateFile("CallOfTheWild.txt", GENERIC_READ, 0u,
               IntPtr.Zero, OPEN_EXISTING,
               FILE_ATTRIBUTE_NORMAL ||| FILE_FLAG_OVERLAPPED,
               IntPtr.Zero)

if hnd.IsInvalid then
    let ex = Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error())
    printfn $"Attempt to open file failed:\n  {ex.Message}"
else
    printfn "File successfully opened."
    hnd.Close()

// If the file cannot be found, the example displays the following output:
//    Attempt to open file failed:
//      The system cannot find the file specified. (Exception from HRESULT: 0x80070002)
Imports Microsoft.Win32.SafeHandles
Imports System.Runtime.InteropServices

Module Example
   Private Const GENERIC_READ As UInteger = 2147483648
   Private Const OPEN_EXISTING As UInteger = 3 
   Private Const FILE_ATTRIBUTE_NORMAL As UInteger = 128
   Private Const FILE_FLAG_OVERLAPPED As UInteger = &h40000000

   Private Declare Auto Function CreateFile Lib "Kernel32" Alias "CreateFileW" (
            lpFileName As String, dwDesiredAccess As UInt32, 
            dwShareMode As UInt32, pSecurityAttributes As IntPtr, 
            dwCreationDisposition As UInt32, dwFlagsAndAttributes As UInt32, 
            hTemplateFile As IntPtr) As SafeFileHandle

   Public Sub Main()
      Dim hnd As SafeFileHandle = CreateFile("CallOfTheWild.txt", GENERIC_READ, 0, 
                                             IntPtr.Zero, OPEN_EXISTING,
                                             FILE_ATTRIBUTE_NORMAL Or FILE_FLAG_OVERLAPPED, 
                                             IntPtr.Zero)
      If hnd.IsInvalid Then
         Dim ex As Exception = Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error())
         Console.WriteLine("Attempt to open file failed:")
         Console.WriteLine("  {0}", ex.Message)
         Return           
      Else 
         Console.WriteLine("File successfully opened.")
         hnd.Close()     
      End If
   End Sub
End Module
' If the file cannot be found, the example displays the following output:
'    Attempt to open file failed:
'      The system cannot find the file specified. (Exception from HRESULT: 0x80070002)

注意

雖然 Zero 對於 null Windows API 函式,其參數或傳回值可以是指標或 nullZero 但不等於 nullnull傳遞至 IntPtr.Zero.Equals 方法一律會傳 false 回 。

您也可以藉由比較傳回的值與 來測試 null 來自 Windows API 函式呼叫的傳回值,以傳回指標或 nullIntPtr.Zero 例如,下列範例中函式的呼叫 GetWindow 會嘗試擷取不存在視窗的控制碼。 如果從 Unmanaged 程式碼呼叫函式,則函式會傳回 null ,但從 Managed 程式碼呼叫時,它會傳 IntPtr.Zero 回 。

using System;
using System.Runtime.InteropServices;

public class Example
{
   private const int GW_OWNER = 4;

   [DllImport("user32", CharSet=CharSet.Auto, SetLastError=true, ExactSpelling=true)]
   public static extern IntPtr GetWindow(IntPtr hwnd, int wFlag);

   public static void Main()
   {
      IntPtr hwnd = new IntPtr(3);
      IntPtr hOwner = GetWindow(hwnd, GW_OWNER);
      if (hOwner == IntPtr.Zero)
         Console.WriteLine("Window not found.");
   }
}
// The example displays the following output:
//        Window not found.
open System
open System.Runtime.InteropServices

let GW_OWNER = 4

[<DllImport("user32", CharSet=CharSet.Auto, SetLastError=true, ExactSpelling=true)>]
extern IntPtr GetWindow(nativeint hwnd, int wFlag)

let hwnd = IntPtr 3
let hOwner = GetWindow(hwnd, GW_OWNER)
if hOwner = IntPtr.Zero then
    printfn "Window not found."

// The example displays the following output:
//        Window not found.
Module Example
   Private Const GW_OWNER As Integer = 4

   Private Declare Function GetWindow Lib "user32" (hWnd As IntPtr, 
                            wFlag As Integer) As IntPtr 

   Public Sub Main()
      Dim hwnd = new IntPtr(3)
      Dim hOwner As IntPtr = GetWindow(hwnd, GW_OWNER)
      If hOwner = IntPtr.Zero Then
         Console.WriteLine("Window not found.")
      End If   
   End Sub
End Module
' The example displays the following output:
'       Window not found.

適用於