NullReferenceException Sınıf

Tanım

Null nesne başvurusunu başvuru girişimi olduğunda oluşturulan özel durum.The exception that is thrown when there is an attempt to dereference a null object reference.

public ref class NullReferenceException : Exception
public ref class NullReferenceException : SystemException
public class NullReferenceException : Exception
public class NullReferenceException : SystemException
[System.Serializable]
public class NullReferenceException : SystemException
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class NullReferenceException : SystemException
type NullReferenceException = class
    inherit Exception
type NullReferenceException = class
    inherit SystemException
[<System.Serializable>]
type NullReferenceException = class
    inherit SystemException
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type NullReferenceException = class
    inherit SystemException
Public Class NullReferenceException
Inherits Exception
Public Class NullReferenceException
Inherits SystemException
Devralma
NullReferenceException
Devralma
NullReferenceException
Öznitelikler

Açıklamalar

NullReferenceExceptionDeğeri olan bir tür üzerindeki bir üyeye erişmeye çalıştığınızda bir özel durum oluşturulur null .A NullReferenceException exception is thrown when you try to access a member on a type whose value is null. Bir NullReferenceException özel durum genellikle geliştirici hatasını yansıtır ve aşağıdaki senaryolarda oluşturulur:A NullReferenceException exception typically reflects developer error and is thrown in the following scenarios:

  • Bir başvuru türü örneğini kaldırmayı unutmuş olabilirsiniz.You've forgotten to instantiate a reference type. Aşağıdaki örnekte, names bildirilmiştir ancak hiçbir şekilde örneklenemez:In the following example, names is declared but never instantiated:

    using System;
    using System.Collections.Generic;
    
    public class Example
    {
       public static void Main(string[] args)
       {
          int value = Int32.Parse(args[0]);
          List<String> names;
          if (value > 0)
             names = new List<String>();
    
          names.Add("Major Major Major");
       }
    }
    // Compilation displays a warning like the following:
    //    Example1.cs(10) : warning BC42104: Variable //names// is used before it
    //    has been assigned a value. A null reference exception could result
    //    at runtime.
    //
    //          names.Add("Major Major Major")
    //          ~~~~~
    // The example displays output like the following output:
    //    Unhandled Exception: System.NullReferenceException: Object reference
    //    not set to an instance of an object.
    //       at Example.Main()
    
    Imports System.Collections.Generic
    
    Module Example
       Public Sub Main()
          Dim names As List(Of String)
          names.Add("Major Major Major")       
       End Sub
    End Module
    ' Compilation displays a warning like the following:
    '    Example1.vb(10) : warning BC42104: Variable 'names' is used before it 
    '    has been assigned a value. A null reference exception could result 
    '    at runtime.
    '    
    '          names.Add("Major Major Major")
    '          ~~~~~
    ' The example displays output like the following output:
    '    Unhandled Exception: System.NullReferenceException: Object reference 
    '    not set to an instance of an object.
    '       at Example.Main()
    

    Bazı derleyiciler, bu kodu derlerken bir uyarı verebilir.Some compilers issue a warning when they compile this code. Diğerleri bir hata ve derleme başarısız olur.Others issue an error, and the compilation fails. Bu sorunu gidermek için, nesnesinin değeri artık olmayacak şekilde örneğini oluşturun null .To address this problem, instantiate the object so that its value is no longer null. Aşağıdaki örnek, bir türün sınıf oluşturucusunu çağırarak bunu yapar.The following example does this by calling a type's class constructor.

    using System;
    using System.Collections.Generic;
    
    public class Example
    {
       public static void Main()
       {
          List<String> names = new List<String>();
          names.Add("Major Major Major");
       }
    }
    
    Imports System.Collections.Generic
    
    Module Example
       Public Sub Main()
          Dim names As New List(Of String)()
          names.Add("Major Major Major")       
       End Sub
    End Module
    
  • Bir diziyi başlatmadan önce boyutun boyutunu unuttunuz.You've forgotten to dimension an array before initializing it. Aşağıdaki örnekte, values bir tamsayı dizisi olacak şekilde bildirilmiştir, ancak içerdiği öğe sayısı hiç belirtilmemiş.In the following example, values is declared to be an integer array, but the number of elements that it contains is never specified. Bu nedenle, değerlerini başlatma denemesi bir NullReferenceException özel durum oluşturdu.The attempt to initialize its values therefore thrown a NullReferenceException exception.

    using System;
    
    public class Example
    {
       public static void Main()
       {
           int[] values = null;
           for (int ctr = 0; ctr <= 9; ctr++)
              values[ctr] = ctr * 2;
    
           foreach (var value in values)
              Console.WriteLine(value);
       }
    }
    // The example displays the following output:
    //    Unhandled Exception:
    //       System.NullReferenceException: Object reference not set to an instance of an object.
    //       at Example.Main()
    
    Module Example
       Public Sub Main()
           Dim values() As Integer
           For ctr As Integer = 0 To 9
              values(ctr) = ctr * 2
           Next
              
           For Each value In values
              Console.WriteLine(value)
           Next      
       End Sub
    End Module
    ' The example displays the following output:
    '    Unhandled Exception: 
    '       System.NullReferenceException: Object reference not set to an instance of an object.
    '       at Example.Main()
    

    Aşağıdaki örnekte olduğu gibi, başlatmadan önce dizideki öğelerin sayısını bildirerek özel durumu ortadan kaldırabilirsiniz.You can eliminate the exception by declaring the number of elements in the array before initializing it, as the following example does.

    using System;
    
    public class Example
    {
       public static void Main()
       {
           int[] values = new int[10];
           for (int ctr = 0; ctr <= 9; ctr++)
              values[ctr] = ctr * 2;
    
           foreach (var value in values)
              Console.WriteLine(value);
       }
    }
    // The example displays the following output:
    //    0
    //    2
    //    4
    //    6
    //    8
    //    10
    //    12
    //    14
    //    16
    //    18
    
    Module Example
       Public Sub Main()
           Dim values(9) As Integer
           For ctr As Integer = 0 To 9
              values(ctr) = ctr * 2
           Next
              
           For Each value In values
              Console.WriteLine(value)
           Next      
       End Sub
    End Module
    ' The example displays the following output:
    '    0
    '    2
    '    4
    '    6
    '    8
    '    10
    '    12
    '    14
    '    16
    '    18
    

    Dizileri bildirme ve başlatma hakkında daha fazla bilgi için bkz. diziler ve diziler.For more information on declaring and initializing arrays, see Arrays and Arrays.

  • Bir yöntemden null dönüş değeri alırsınız ve ardından döndürülen türde bir yöntemi çağırın.You get a null return value from a method, and then call a method on the returned type. Bu, bazen bir belge hatasının sonucudur; belgeler bir yöntem çağrısının dönebileceğini unutmayın null .This sometimes is the result of a documentation error; the documentation fails to note that a method call can return null. Diğer durumlarda, kodunuz yanlışlıkla yöntemin her zaman null olmayan bir değer döndürdüğünü varsayar.In other cases, your code erroneously assumes that the method will always return a non-null value.

    Aşağıdaki örnekteki kod, Array.Find yöntemin her zaman, Person FirstName alanı bir arama dizesiyle eşleşen nesneyi döndürdüğünü varsayar.The code in the following example assumes that the Array.Find method always returns Person object whose FirstName field matches a search string. Eşleşme olmadığından, çalışma zamanı bir NullReferenceException özel durum oluşturur.Because there is no match, the runtime throws a NullReferenceException exception.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          Person[] persons = Person.AddRange( new String[] { "Abigail", "Abra",
                                              "Abraham", "Adrian", "Ariella",
                                              "Arnold", "Aston", "Astor" } );
          String nameToFind = "Robert";
          Person found = Array.Find(persons, p => p.FirstName == nameToFind);
          Console.WriteLine(found.FirstName);
       }
    }
    
    public class Person
    {
       public static Person[] AddRange(String[] firstNames)
       {
          Person[] p = new Person[firstNames.Length];
          for (int ctr = 0; ctr < firstNames.Length; ctr++)
             p[ctr] = new Person(firstNames[ctr]);
    
          return p;
       }
    
       public Person(String firstName)
       {
          this.FirstName = firstName;
       }
    
       public String FirstName;
    }
    // The example displays the following output:
    //       Unhandled Exception: System.NullReferenceException:
    //       Object reference not set to an instance of an object.
    //          at Example.Main()
    
    Module Example
       Public Sub Main()
          Dim persons() As Person = Person.AddRange( { "Abigail", "Abra",
                                                       "Abraham", "Adrian",
                                                       "Ariella", "Arnold", 
                                                       "Aston", "Astor" } )    
          Dim nameToFind As String = "Robert"
          Dim found As Person = Array.Find(persons, Function(p) p.FirstName = nameToFind)
          Console.WriteLine(found.FirstName)
       End Sub
    End Module
    
    Public Class Person
       Public Shared Function AddRange(firstNames() As String) As Person()
          Dim p(firstNames.Length - 1) As Person
          For ctr As Integer = 0 To firstNames.Length - 1
             p(ctr) = New Person(firstNames(ctr))
          Next   
          Return p
       End Function
       
       Public Sub New(firstName As String)
          Me.FirstName = firstName
       End Sub 
       
       Public FirstName As String
    End Class
    ' The example displays the following output:
    '       Unhandled Exception: System.NullReferenceException: 
    '       Object reference not set to an instance of an object.
    '          at Example.Main()
    

    Bu sorunu gidermek için yöntemin dönüş değerini test etmek için, null Aşağıdaki örnekte olduğu gibi, üyelerinden herhangi birini çağırmadan önce olmamasını sağlayın.To address this problem, test the method's return value to ensure that it is not null before calling any of its members, as the following example does.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          Person[] persons = Person.AddRange( new String[] { "Abigail", "Abra",
                                              "Abraham", "Adrian", "Ariella",
                                              "Arnold", "Aston", "Astor" } );
          String nameToFind = "Robert";
          Person found = Array.Find(persons, p => p.FirstName == nameToFind);
          if (found != null)
             Console.WriteLine(found.FirstName);
          else
             Console.WriteLine("{0} not found.", nameToFind);
       }
    }
    
    public class Person
    {
       public static Person[] AddRange(String[] firstNames)
       {
          Person[] p = new Person[firstNames.Length];
          for (int ctr = 0; ctr < firstNames.Length; ctr++)
             p[ctr] = new Person(firstNames[ctr]);
    
          return p;
       }
    
       public Person(String firstName)
       {
          this.FirstName = firstName;
       }
    
       public String FirstName;
    }
    // The example displays the following output:
    //        Robert not found
    
    Module Example
       Public Sub Main()
          Dim persons() As Person = Person.AddRange( { "Abigail", "Abra",
                                                       "Abraham", "Adrian",
                                                       "Ariella", "Arnold", 
                                                       "Aston", "Astor" } )    
          Dim nameToFind As String = "Robert"
          Dim found As Person = Array.Find(persons, Function(p) p.FirstName = nameToFind)
          If found IsNot Nothing Then
             Console.WriteLine(found.FirstName)
          Else
             Console.WriteLine("{0} not found.", nameToFind)
          End If   
       End Sub
    End Module
    
    Public Class Person
       Public Shared Function AddRange(firstNames() As String) As Person()
          Dim p(firstNames.Length - 1) As Person
          For ctr As Integer = 0 To firstNames.Length - 1
             p(ctr) = New Person(firstNames(ctr))
          Next   
          Return p
       End Function
       
       Public Sub New(firstName As String)
          Me.FirstName = firstName
       End Sub 
       
       Public FirstName As String
    End Class
    ' The example displays the following output:
    '       Robert not found
    
  • Bir ifade kullanıyorsunuz (örneğin, bir değeri almak için bir yöntem veya özellik listesini birlikte zincirliyoruz) ve değerin ne olduğunu kontrol ediyor, ancak null çalışma zamanı bir NullReferenceException özel durum oluşturur.You're using an expression (for example, you're chaining a list of methods or properties together) to retrieve a value and, although you're checking whether the value is null, the runtime still throws a NullReferenceException exception. Bu, ifadedeki ara değerlerden biri döndürdüğü için oluşur null .This occurs because one of the intermediate values in the expression returns null. Sonuç olarak, testiniz null hiçbir şekilde değerlendirilmez.As a result, your test for null is never evaluated.

    Aşağıdaki örnek, Pages nesneleri tarafından sunulan Web sayfaları hakkında bilgileri önbelleğe alan bir nesnesi tanımlar Page .The following example defines a Pages object that caches information about web pages, which are presented by Page objects. Example.MainYöntemi, geçerli Web sayfasının null olmayan bir başlığa sahip olup olmadığını denetler ve varsa başlığı görüntüler.The Example.Main method checks whether the current web page has a non-null title and, if it does, displays the title. Ancak, bu denetim olmasına rağmen Yöntem bir NullReferenceException özel durum oluşturur.Despite this check, however, the method throws a NullReferenceException exception.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          var pages = new Pages();
          if (! String.IsNullOrEmpty(pages.CurrentPage.Title)) {
             String title = pages.CurrentPage.Title;
             Console.WriteLine("Current title: '{0}'", title);
          }
       }
    }
    
    public class Pages
    {
       Page[] page = new Page[10];
       int ctr = 0;
    
       public Page CurrentPage
       {
          get { return page[ctr]; }
          set {
             // Move all the page objects down to accommodate the new one.
             if (ctr > page.GetUpperBound(0)) {
                for (int ndx = 1; ndx <= page.GetUpperBound(0); ndx++)
                   page[ndx - 1] = page[ndx];
             }
             page[ctr] = value;
             if (ctr < page.GetUpperBound(0))
                ctr++;
          }
       }
    
       public Page PreviousPage
       {
          get {
             if (ctr == 0) {
                if (page[0] == null)
                   return null;
                else
                   return page[0];
             }
             else {
                ctr--;
                return page[ctr + 1];
             }
          }
       }
    }
    
    public class Page
    {
       public Uri URL;
       public String Title;
    }
    // The example displays the following output:
    //    Unhandled Exception:
    //       System.NullReferenceException: Object reference not set to an instance of an object.
    //       at Example.Main()
    
    Module Example
       Public Sub Main()
          Dim pages As New Pages()
          Dim title As String = pages.CurrentPage.Title
       End Sub
    End Module
    
    Public Class Pages 
       Dim page(9) As Page
       Dim ctr As Integer = 0
       
       Public Property CurrentPage As Page
          Get
             Return page(ctr)
          End Get
          Set
             ' Move all the page objects down to accommodate the new one.
             If ctr > page.GetUpperBound(0) Then
                For ndx As Integer = 1 To page.GetUpperBound(0)
                   page(ndx - 1) = page(ndx)
                Next
             End If    
             page(ctr) = value
             If ctr < page.GetUpperBound(0) Then ctr += 1 
          End Set
       End Property
       
       Public ReadOnly Property PreviousPage As Page
          Get
             If ctr = 0 Then 
                If page(0) Is Nothing Then
                   Return Nothing
                Else
                   Return page(0)
                End If   
             Else
                ctr -= 1
                Return page(ctr + 1)
             End If
          End Get
       End Property         
    End Class
    
    Public Class Page
       Public URL As Uri
       Public Title As String
    End Class
    ' The example displays the following output:
    '    Unhandled Exception: 
    '       System.NullReferenceException: Object reference not set to an instance of an object.
    '       at Example.Main()
    

    Özel durum, pages.CurrentPage null önbellekte hiçbir sayfa bilgisi depolanmadığı için döndürülür.The exception is thrown because pages.CurrentPage returns null if no page information is stored in the cache. Bu özel durum, CurrentPage Page Title Aşağıdaki örnekte olduğu gibi geçerli nesnenin özelliği alınmadan önce özelliğin değeri test edilirken düzeltilebilir:This exception can be corrected by testing the value of the CurrentPage property before retrieving the current Page object's Title property, as the following example does:

    using System;
    
    public class Example
    {
       public static void Main()
       {
          var pages = new Pages();
          Page current = pages.CurrentPage;
          if (current != null) {
             String title = current.Title;
             Console.WriteLine("Current title: '{0}'", title);
          }
          else {
             Console.WriteLine("There is no page information in the cache.");
          }
       }
    }
    // The example displays the following output:
    //       There is no page information in the cache.
    
    Module Example
       Public Sub Main()
          Dim pages As New Pages()
          Dim current As Page = pages.CurrentPage
          If current IsNot Nothing Then 
             Dim title As String = current.Title
             Console.WriteLine("Current title: '{0}'", title)
          Else
             Console.WriteLine("There is no page information in the cache.")
          End If   
       End Sub
    End Module
    ' The example displays the following output:
    '       There is no page information in the cache.
    
  • Başvuru türleri içeren bir dizinin öğelerini numaralandırıyor ve öğelerinden birini işleme denemeniz NullReferenceException özel durum oluşturur.You're enumerating the elements of an array that contains reference types, and your attempt to process one of the elements throws a NullReferenceException exception.

    Aşağıdaki örnek bir dize dizisi tanımlar.The following example defines a string array. Bir for ifade dizideki öğeleri numaralandırır ve Trim dizeyi görüntülemeden önce her bir dizenin yöntemini çağırır.A for statement enumerates the elements in the array and calls each string's Trim method before displaying the string.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          String[] values = { "one", null, "two" };
          for (int ctr = 0; ctr <= values.GetUpperBound(0); ctr++)
             Console.Write("{0}{1}", values[ctr].Trim(),
                           ctr == values.GetUpperBound(0) ? "" : ", ");
          Console.WriteLine();
       }
    }
    // The example displays the following output:
    //    Unhandled Exception:
    //       System.NullReferenceException: Object reference not set to an instance of an object.
    //       at Example.Main()
    
    Module Example
       Public Sub Main()
          Dim values() As String = { "one", Nothing, "two" }
          For ctr As Integer = 0 To values.GetUpperBound(0)
             Console.Write("{0}{1}", values(ctr).Trim(), 
                           If(ctr = values.GetUpperBound(0), "", ", ")) 
          Next
          Console.WriteLine()
       End Sub
    End Module
    ' The example displays the following output:
    '    Unhandled Exception: System.NullReferenceException: 
    '       Object reference not set to an instance of an object.
    '       at Example.Main()
    

    Bu özel durum, dizideki her bir öğenin null olmayan bir değer içermesi gerektiğini varsayırsanız ve dizi öğesinin değeri aslında olduğunda oluşur null .This exception occurs if you assume that each element of the array must contain a non-null value, and the value of the array element is in fact null. nullAşağıdaki örnekte gösterildiği gibi, öğenin bu öğe üzerinde herhangi bir işlem gerçekleştirmesinden önce olup olmadığı test ederek, özel durum ortadan kaldırılabilir.The exception can be eliminated by testing whether the element is null before performing any operation on that element, as the following example shows.

    using System;
    
    public class Example
    {
       public static void Main()
       {
          String[] values = { "one", null, "two" };
          for (int ctr = 0; ctr <= values.GetUpperBound(0); ctr++)
             Console.Write("{0}{1}",
                           values[ctr] != null ? values[ctr].Trim() : "",
                           ctr == values.GetUpperBound(0) ? "" : ", ");
          Console.WriteLine();
       }
    }
    // The example displays the following output:
    //       one, , two
    
    Module Example
       Public Sub Main()
          Dim values() As String = { "one", Nothing, "two" }
          For ctr As Integer = 0 To values.GetUpperBound(0)
             Console.Write("{0}{1}", 
                           If(values(ctr) IsNot Nothing, values(ctr).Trim(), ""), 
                           If(ctr = values.GetUpperBound(0), "", ", ")) 
          Next
          Console.WriteLine()
       End Sub
    End Module
    ' The example displays the following output:
    '       one, , two
    
  • NullReferenceExceptionGeçirilen bir yöntem tarafından özel durum oluşturuldu null .A NullReferenceException exception is thrown by a method that is passed null. Bazı yöntemler, bunlara geçirilen bağımsız değişkenleri doğrular.Some methods validate the arguments that are passed to them. Bunu yaptıysanız ve bağımsız değişkenlerden biri ise null , yöntem bir System.ArgumentNullException özel durum oluşturur.If they do and one of the arguments is null, the method throws an System.ArgumentNullException exception. Aksi takdirde, bir NullReferenceException özel durum oluşturur.Otherwise, it throws a NullReferenceException exception. Aşağıdaki örnekte bu senaryo gösterilmektedir.The following example illustrates this scenario.

    using System;
    using System.Collections.Generic;
    
    public class Example
    {
       public static void Main()
       {
          List<String> names = GetData();
          PopulateNames(names);
       }
    
       private static void PopulateNames(List<String> names)
       {
          String[] arrNames = { "Dakota", "Samuel", "Nikita",
                                "Koani", "Saya", "Yiska", "Yumaevsky" };
          foreach (var arrName in arrNames)
             names.Add(arrName);
       }
    
       private static List<String> GetData()
       {
          return null;
       }
    }
    // The example displays output like the following:
    //    Unhandled Exception: System.NullReferenceException: Object reference
    //    not set to an instance of an object.
    //       at Example.PopulateNames(List`1 names)
    //       at Example.Main()
    
    Imports System.Collections.Generic
    
    Module Example
       Public Sub Main()
          Dim names As List(Of String) = GetData()
          PopulateNames(names)
       End Sub
       
       Private Sub PopulateNames(names As List(Of String))
          Dim arrNames() As String = { "Dakota", "Samuel", "Nikita",
                                       "Koani", "Saya", "Yiska", "Yumaevsky" }
          For Each arrName In arrNames
             names.Add(arrName)
          Next
       End Sub
       
       Private Function GetData() As List(Of String)
          Return Nothing   
       End Function
    End Module
    ' The example displays output like the following:
    '    Unhandled Exception: System.NullReferenceException: Object reference 
    '    not set to an instance of an object.
    '       at Example.PopulateNames(List`1 names)
    '       at Example.Main()
    

    Bu sorunu gidermek için yönteme geçirilen bağımsız değişkenin olmadığından emin olun null veya bir blokta oluşturulan özel durumu işleyin try…catch…finally .To address this issue, make sure that the argument passed to the method is not null, or handle the thrown exception in a try…catch…finally block. Daha fazla bilgi için bkz. özel durumlar.For more information, see Exceptions.

Aşağıdaki Microsoft ara dili (MSIL) yönergeleri şunu oluşturur NullReferenceException : callvirt , cpblk ,,, cpobj initblk ldelem.<type> , ldelema , ldfld , ldflda , ldind.<type> , ldlen , stelem.<type> , stfld , stind.<type> ,, throw ve unbox .The following Microsoft intermediate language (MSIL) instructions throw NullReferenceException: callvirt, cpblk, cpobj, initblk, ldelem.<type>, ldelema, ldfld, ldflda, ldind.<type>, ldlen, stelem.<type>, stfld, stind.<type>, throw, and unbox.

NullReferenceException 0x80004003 değerine sahip olan HRESULT COR_E_NULLREFERENCE kullanır.NullReferenceException uses the HRESULT COR_E_NULLREFERENCE, which has the value 0x80004003.

Bir örneğinin ilk özellik değerlerinin listesi için NullReferenceException , NullReferenceException oluşturuculara bakın.For a list of initial property values for an instance of NullReferenceException, see the NullReferenceException constructors.

Yayın kodunda NullReferenceException işlemeHandling NullReferenceException in release code

Bir NullReferenceException, oluştuktan sonra işlemek yerine kullanmaktan kaçınmak için genellikle daha iyidir.It's usually better to avoid a NullReferenceException than to handle it after it occurs. Bir özel durumu işlemek, kodunuzun bakımını ve anlaşılması daha zor hale getirebilir ve bazen diğer hataları ortaya çıkarabilir.Handling an exception can make your code harder to maintain and understand, and can sometimes introduce other bugs. NullReferenceException genellikle kurtarılabilir olmayan bir hatadır.A NullReferenceException is often a non-recoverable error. Bu durumlarda, özel durumun uygulamanın durdurulmasına izin vermek en iyi alternatif olabilir.In these cases, letting the exception stop the app might be the best alternative.

Ancak, hatanın işlenmesi yararlı olabilecek birçok durum vardır:However, there are many situations where handling the error can be useful:

  • Uygulamanız null olan nesneleri yok sayabilir.Your app can ignore objects that are null. Örneğin, uygulamanız kayıtları bir veritabanında alıp işliyorsa, null nesneler ile sonuçlanan bazı hatalı kayıtları yoksayabilirsiniz.For example, if your app retrieves and processes records in a database, you might be able to ignore some number of bad records that result in null objects. Hatalı verileri bir günlük dosyasında veya uygulama kullanıcı arabiriminde kaydetmek, tek yapmanız gerekebilecek bir işlem olabilir.Recording the bad data in a log file or in the application UI might be all you have to do.

  • Özel durumdan kurtarma yapabilirsiniz.You can recover from the exception. Örneğin, bağlantı kaybolursa veya bağlantı zaman aşımına uğrarsa, başvuru türü döndüren bir Web hizmetine yapılan çağrı null döndürebilir. Bağlantıyı yeniden kurmayı deneyebilir ve çağrıyı tekrar deneyebilirsiniz.For example, a call to a web service that returns a reference type might return null if the connection is lost or the connection times out. You can attempt to reestablish the connection and try the call again.

  • Uygulamanızın durumunu geçerli bir duruma geri yükleyebilirsiniz.You can restore the state of your app to a valid state. Örneğin, bir NullReferenceException ' i oluşturan bir yöntemi çağırmadan önce bir veri deposuna bilgi kaydetmenizi gerektiren çok adımlı bir görev gerçekleştiriyor olabilirsiniz.For example, you might be performing a multi-step task that requires you to save information to a data store before you call a method that throws a NullReferenceException. Başlatılmamış nesne veri kaydını bozsa, uygulamayı kapatmadan önce önceki verileri kaldırabilirsiniz.If the uninitialized object would corrupt the data record, you can remove the previous data before you close the app.

  • Özel durumu raporlamak istiyorsunuz.You want to report the exception. Örneğin, hata, uygulamanızın kullanıcısının bir hatasından kaynaklandıysa, doğru bilgileri sağlamaya yardımcı olmak için bir ileti oluşturabilirsiniz.For example, if the error was caused by a mistake from the user of your app, you can generate a message to help him supply the correct information. Sorunu gidermenize yardımcı olması için hata hakkındaki bilgileri de günlüğe kaydedebilirsiniz.You can also log information about the error to help you fix the problem. ASP.NET gibi bazı çerçeveler, uygulamanın hiçbir şekilde kilitlenmeyeceğinden tüm hataları yakalayan bir üst düzey özel durum işleyicisine sahiptir; Bu durumda, özel durumu günlüğe kaydetme işleminin oluştuğunu bildiğiniz tek yolu olabilir.Some frameworks, like ASP.NET, have a high-level exception handler that captures all errors to that the app never crashes; in that case, logging the exception might be the only way you can know that it occurs.

Oluşturucular

NullReferenceException()

Sınıfının yeni bir örneğini başlatır NullReferenceException ve Message Yeni Örneğin özelliğini, hatayı açıklayan sistem tarafından sağlanan bir ileti olarak ayarlar; Örneğin, "bir nesne örneğinin gerekli olduğu yerde ' null ' değeri bulundu."Initializes a new instance of the NullReferenceException class, setting the Message property of the new instance to a system-supplied message that describes the error, such as "The value 'null' was found where an instance of an object was required." Bu ileti, geçerli sistem kültürünü göz önünde bulundurur.This message takes into account the current system culture.

NullReferenceException(SerializationInfo, StreamingContext)

NullReferenceException sınıfının yeni bir örneğini serileştirilmiş verilerle başlatır.Initializes a new instance of the NullReferenceException class with serialized data.

NullReferenceException(String)

Belirtilen bir hata iletisiyle sınıfın yeni bir örneğini başlatır NullReferenceException .Initializes a new instance of the NullReferenceException class with a specified error message.

NullReferenceException(String, Exception)

NullReferenceExceptionBelirtilen bir hata iletisiyle sınıfın yeni bir örneğini ve bu özel durumun nedeni olan iç özel duruma bir başvuruyu başlatır.Initializes a new instance of the NullReferenceException class with a specified error message and a reference to the inner exception that is the cause of this exception.

Özellikler

Data

Özel durum hakkında ek kullanıcı tanımlı bilgiler sağlayan anahtar/değer çiftleri koleksiyonunu alır.Gets a collection of key/value pairs that provide additional user-defined information about the exception.

(Devralındığı yer: Exception)
HelpLink

Bu özel durumla ilişkili Yardım dosyasının bağlantısını alır veya ayarlar.Gets or sets a link to the help file associated with this exception.

(Devralındığı yer: Exception)
HResult

Belirli bir özel duruma atanan kodlanmış bir sayısal değer olan HRESULT 'yi alır veya ayarlar.Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.

(Devralındığı yer: Exception)
InnerException

ExceptionGeçerli özel duruma neden olan örneği alır.Gets the Exception instance that caused the current exception.

(Devralındığı yer: Exception)
Message

Geçerli özel durumu açıklayan bir ileti alır.Gets a message that describes the current exception.

(Devralındığı yer: Exception)
Source

Uygulamanın veya hataya neden olan nesnenin adını alır veya ayarlar.Gets or sets the name of the application or the object that causes the error.

(Devralındığı yer: Exception)
StackTrace

Çağrı yığınında anlık çerçevelerin dize gösterimini alır.Gets a string representation of the immediate frames on the call stack.

(Devralındığı yer: Exception)
TargetSite

Geçerli özel durumu oluşturan yöntemi alır.Gets the method that throws the current exception.

(Devralındığı yer: Exception)

Yöntemler

Equals(Object)

Belirtilen nesnenin geçerli nesneye eşit olup olmadığını belirler.Determines whether the specified object is equal to the current object.

(Devralındığı yer: Object)
GetBaseException()

Türetilmiş bir sınıfta geçersiz kılınırsa, Exception bir veya daha fazla sonraki özel durumun kök nedeni olan öğesini döndürür.When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.

(Devralındığı yer: Exception)
GetHashCode()

Varsayılan karma işlevi olarak işlev görür.Serves as the default hash function.

(Devralındığı yer: Object)
GetObjectData(SerializationInfo, StreamingContext)

Türetilmiş bir sınıfta geçersiz kılınırsa, SerializationInfo özel durum hakkındaki bilgileri ayarlar.When overridden in a derived class, sets the SerializationInfo with information about the exception.

(Devralındığı yer: Exception)
GetType()

Geçerli örneğin çalışma zamanı türünü alır.Gets the runtime type of the current instance.

(Devralındığı yer: Exception)
MemberwiseClone()

Geçerli bir basit kopyasını oluşturur Object .Creates a shallow copy of the current Object.

(Devralındığı yer: Object)
ToString()

Geçerli özel durumun dize gösterimini oluşturur ve döndürür.Creates and returns a string representation of the current exception.

(Devralındığı yer: Exception)

Ekinlikler

SerializeObjectState

Özel durum hakkında serileştirilmiş veri içeren bir özel durum nesnesi oluşturmak için bir özel durum serileştirildiğinde gerçekleşir.Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception.

(Devralındığı yer: Exception)

Şunlara uygulanır

Ayrıca bkz.