IntPtr.Zero 欄位

定義

表示已經初始化為零的指標或控點之唯讀欄位。A read-only field that represents a pointer or handle that has been initialized to zero.

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

欄位值

備註

此欄位的值不null等於。The value of this field is not equivalent to null. 使用此欄位可有效率地判斷實例IntPtr是否已設定為零以外的值。Use this field to efficiently determine whether an instance of IntPtr has been set to a value other than zero.

例如,假設變數(ip)是的IntPtr實例。For example, assume the variable, ip, is an instance of IntPtr. 您可以藉由比較它與由函式傳回的值來判斷是否已設定,例如: " if ip != new IntPtr(0)... "。You can determine if it has been set by comparing it to the value returned by a constructor, for example: " if ip != new IntPtr(0)... ". 不過,叫用函式以取得未初始化的指標沒有效率。However, invoking a constructor to get an uninitialized pointer is inefficient. 最好是以 " if ip != IntPtr.Zero... " 或 " if !IntPtr.Zero.Equals(ip)... " 撰寫程式碼。It is better to code either " if ip != IntPtr.Zero... ", or " if !IntPtr.Zero.Equals(ip)... ".

從 managed 程式碼呼叫 Windows API 時, IntPtr.Zero null如果引數應該是指標或null,您可以傳遞而不是。When calling the Windows API from managed code, you can pass IntPtr.Zero instead of null if an argument is expected to be either a pointer or a null. 例如, CreateFile下列對 Windows 函數的呼叫會提供IntPtr.Zero pSecurityAttributeshTemplateFile引數值。For example, the following call to the Windows CreateFile function supplies IntPtr.Zero for the pSecurityAttributes and hTemplateFile argument values.

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)
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對具有參數或傳回值(可以是指標或null)的 Windows API 函式相當於Zero ,但不null等於。Although Zero is equivalent to null for Windows API functions with parameters or return values that can be either pointers or null, Zero is not equivalent to null. 傳遞nullIntPtr.Zero.Equals方法一律會傳回falsePassing null to the IntPtr.Zero.Equals method always returns false.

您也可以藉由比較null傳回的值與IntPtr.Zero,從傳回指標或的null Windows API 函式呼叫中測試傳回值。You can also test for a null return value from Windows API function calls that return either a pointer or a null by comparing the returned value with IntPtr.Zero. 例如,在下列範例中, GetWindow對函式的呼叫會嘗試取出不存在之視窗的控制碼。For example, the call to the GetWindow function in the following example tries to retrieve the handle of a non-existent window. 如果從非受控碼呼叫該函式,函式null會傳回,但從 managed 程式碼呼叫它時, IntPtr.Zero它會傳回。If it were called from unmanaged code, the function would return null, but when it is called from managed code, it returns 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.
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.

適用於