NullReferenceException Klasa

Definicja

Wyjątek zgłaszany podczas próby wyłudzenia odwołania do obiektu o wartości null.

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
Dziedziczenie
NullReferenceException
Dziedziczenie
NullReferenceException
Atrybuty

Uwagi

Wyjątek NullReferenceException jest zgłaszany podczas próby uzyskania dostępu do elementu członkowskiego w typie, którego wartość to null. Wyjątek NullReferenceException zazwyczaj odzwierciedla błąd dewelopera i jest zgłaszany w następujących scenariuszach:

  • Nie pamiętasz o utworzeniu wystąpienia typu odwołania. W poniższym przykładzie jest zadeklarowana, names ale nigdy nie utworzono wystąpienia:

    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()
    
    open System
    
    [<EntryPoint>]
    let main args =
        let value = Int32.Parse args[0]
        // Set names to null, don't initialize it. 
        let mutable names = Unchecked.defaultof<ResizeArray<string>>
        if value > 0 then
            names <- ResizeArray()
        names.Add "Major Major Major"
        0
    // Compilation does not display a warning as this is an extremely rare occurance in F#.
    // Creating a value without initalizing either requires using 'null' (not possible
    // on types defined in F# without [<AllowNullLiteral>]) or Unchecked.defaultof.
    //
    // 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()
    

    Niektóre kompilatory wydają ostrzeżenie podczas kompilowania tego kodu. Inne wystawiają błąd, a kompilacja kończy się niepowodzeniem. Aby rozwiązać ten problem, utwórz wystąpienie obiektu tak, aby jego wartość nie przekraczała wartości null. W poniższym przykładzie jest to spowodowane wywołaniem konstruktora klasy typu.

    using System;
    using System.Collections.Generic;
    
    public class Example
    {
       public static void Main()
       {
          List<String> names = new List<String>();
          names.Add("Major Major Major");
       }
    }
    
    let names = ResizeArray()
    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
    
  • Nie pamiętasz o wymiarze tablicy przed jej zainicjowaniem. W poniższym przykładzie values jest deklarowana jako tablica całkowita, ale liczba elementów, które zawiera, nigdy nie jest określona. Próba zainicjowania jego wartości w związku z tym zgłosiła NullReferenceException wyjątek.

    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()
    
    let values: int[] = null
    for i = 0 to 9 do
        values[i] <- i * 2
    
    for value in values do
        printfn $"{value}"
    // The example displays the following output:
    //    Unhandled Exception:
    //       System.NullReferenceException: Object reference not set to an instance of an object.
    //       at <StartupCode$fs>.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()
    

    Wyjątek można wyeliminować, deklarując liczbę elementów w tablicy przed jego zainicjowaniem, jak to robi w poniższym przykładzie.

    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
    
    let values = Array.zeroCreate<int> 10
    for i = 0 to 9 do
        values[i] <- i * 2
    
    for value in values do
        printfn $"{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
    

    Aby uzyskać więcej informacji na temat deklarowania i inicjowania tablic, zobacz Tablice i tablice.

  • Otrzymasz wartość zwracaną o wartości null z metody, a następnie wywołaj metodę w zwracanym typie. Czasami jest to wynik błędu dokumentacji; Nie można zauważyć, że wywołanie metody może zwrócić nullwartość . W innych przypadkach kod błędnie zakłada, że metoda zawsze zwróci wartość inną niż null .

    Kod w poniższym przykładzie zakłada, że Array.Find metoda zawsze zwraca Person obiekt, którego FirstName pole pasuje do ciągu wyszukiwania. Ponieważ nie ma dopasowania, środowisko uruchomieniowe zgłasza NullReferenceException wyjątek.

    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()
    
    open System
    
    type Person(firstName) =
        member _.FirstName = firstName
    
        static member AddRange(firstNames) =
            Array.map Person firstNames
    
    let persons = 
        [| "Abigail"; "Abra"; "Abraham"; "Adrian"
           "Ariella"; "Arnold"; "Aston"; "Astor" |]
        |> Person.AddRange
    
    let nameToFind = "Robert"
    let found = Array.Find(persons, fun p -> p.FirstName = nameToFind)
    
    printfn $"{found.FirstName}"
    
    // The example displays the following output:
    //       Unhandled Exception: System.NullReferenceException:
    //       Object reference not set to an instance of an object.
    //          at <StartupCode$fs>.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()
    

    Aby rozwiązać ten problem, przetestuj wartość zwracaną przez metodę, aby upewnić się, że nie null jest ona przed wywołaniem żadnego z jego elementów członkowskich, jak w poniższym przykładzie.

    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
    
    open System
    
    [<AllowNullLiteral>]
    type Person(firstName) =
        member _.FirstName = firstName
    
        static member AddRange(firstNames) =
            Array.map Person firstNames
    
    let persons = 
        [| "Abigail"; "Abra"; "Abraham"; "Adrian"
           "Ariella"; "Arnold"; "Aston"; "Astor" |]
        |> Person.AddRange
    
    let nameToFind = "Robert"
    let found = Array.Find(persons, fun p -> p.FirstName = nameToFind)
    
    if found <> null then
        printfn $"{found.FirstName}"
    else 
        printfn $"{nameToFind} not found."
    
    // Using F#'s Array.tryFind function
    // This does not require a null check or [<AllowNullLiteral>]
    let found2 = 
        persons |> Array.tryFind (fun p -> p.FirstName = nameToFind)
    
    match found2 with
    | Some firstName ->
        printfn $"{firstName}"
    | None ->
        printfn $"{nameToFind} not found."
    
    // The example displays the following output:
    //        Robert not found.
    //        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
    
  • Używasz wyrażenia (na przykład łączysz listę metod lub właściwości), aby pobrać wartość i, mimo że sprawdzasz, czy wartość to null, środowisko uruchomieniowe nadal zgłasza NullReferenceException wyjątek. Dzieje się tak, ponieważ jedna z wartości pośrednich w wyrażeniu zwraca wartość null. W rezultacie test dla null elementu nigdy nie jest oceniany.

    W poniższym przykładzie zdefiniowano Pages obiekt, który buforuje informacje o stronach internetowych, które są prezentowane przez Page obiekty. Metoda Example.Main sprawdza, czy bieżąca strona internetowa ma tytuł inny niż null, a jeśli tak, wyświetla tytuł. Mimo tego sprawdzenia metoda zgłasza NullReferenceException wyjątek.

    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()
    
    open System
    
    type Page() =
        [<DefaultValue>]
        val mutable public URL: Uri
        [<DefaultValue>]
        val mutable public Title: string
    
    type Pages() =
        let pages = Array.zeroCreate<Page> 10
        let mutable i = 0
    
        member _.CurrentPage
            with get () = pages[i]
            and set (value) =
                // Move all the page objects down to accommodate the new one.
                if i > pages.GetUpperBound 0 then
                    for ndx = 1 to pages.GetUpperBound 0 do
                        pages[ndx - 1] <- pages[ndx]
    
                pages[i] <- value
                if i < pages.GetUpperBound 0 then
                    i <- i + 1
    
        member _.PreviousPage =
            if i = 0 then
                if box pages[0] = null then
                    Unchecked.defaultof<Page>
                else
                    pages[0]
            else
                i <- i - 1
                pages[i + 1]
    
    let pages = Pages()
    if String.IsNullOrEmpty pages.CurrentPage.Title |> not then
        let title = pages.CurrentPage.Title
        printfn $"Current title: '{title}'"
    
    
    // The example displays the following output:
    //    Unhandled Exception:
    //       System.NullReferenceException: Object reference not set to an instance of an object.
    //       at <StartupCode$fs>.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()
    

    Wyjątek jest zgłaszany, ponieważ pages.CurrentPage zwraca wartość , null jeśli żadne informacje o stronie nie są przechowywane w pamięci podręcznej. Ten wyjątek można poprawić, testując wartość CurrentPage właściwości przed pobraniem właściwości bieżącego Page obiektu Title , jak w poniższym przykładzie:

    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.
    
    let pages = Pages()
    let current = pages.CurrentPage
    if box current <> null then
        let title = current.Title
        printfn $"Current title: '{title}'"
    else
        printfn "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.
    
  • Wyliczasz elementy tablicy zawierającej typy referencyjne, a próba przetworzenia jednego z elementów zgłasza NullReferenceException wyjątek.

    W poniższym przykładzie zdefiniowano tablicę ciągów. Instrukcja for wylicza elementy w tablicy i wywołuje metodę każdego ciągu Trim przed wyświetleniem ciągu.

    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()
    
    open System
    
    let values = [| "one"; null; "two" |]
    for i = 0 to values.GetUpperBound 0 do
        printfn $"""{values[i].Trim()}{if i = values.GetUpperBound 0 then "" else ", "}"""
    printfn ""
    // The example displays the following output:
    //    Unhandled Exception:
    //       System.NullReferenceException: Object reference not set to an instance of an object.
    //       at <StartupCode$fs>.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()
    

    Ten wyjątek występuje, jeśli zakładasz, że każdy element tablicy musi zawierać wartość inną niż null, a wartość elementu tablicy jest w rzeczywistości null. Wyjątek można wyeliminować, testując, czy element znajduje się null przed wykonaniem dowolnej operacji na tym elemecie, jak pokazano w poniższym przykładzie.

    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
    
    open System
    
    let values = [| "one"; null; "two" |]
    for i = 0 to values.GetUpperBound 0 do
        printf $"""{if values[i] <> null then values[i].Trim() else ""}{if i = values.GetUpperBound 0 then "" else ", "}"""
    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
    
  • Wyjątek NullReferenceException może zostać zgłoszony przez metodę, gdy uzyskuje dostęp do elementu członkowskiego jednego z jego argumentów, ale ten argument to null. Metoda PopulateNames w poniższym przykładzie zgłasza wyjątek w wierszu names.Add(arrName);.

    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()
    
    let populateNames (names: ResizeArray<string>) =
        let arrNames =
            [ "Dakota"; "Samuel"; "Nikita"
              "Koani"; "Saya"; "Yiska"; "Yumaevsky" ]
        for arrName in arrNames do
            names.Add arrName
    
    let getData () : ResizeArray<string> =
        null
    
    let names = getData ()
    populateNames names
    
    // 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 <StartupCode$fs>.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()
    

    Aby rozwiązać ten problem, upewnij się, że argument przekazany do metody nie nullma wartości , lub obsłuż wyjątek zgłoszony w try…catch…finally bloku. Aby uzyskać więcej informacji, zobacz Wyjątki.

Następujące instrukcje języka microsoft intermediate language (MSIL) zgłaszają następujące instrukcje: , , ldfldaldlencpblkldelem.<type>throwstind.<type>stfldldfldcpobjstelem.<type>ldelemainitblkldind.<type>i .unboxcallvirtNullReferenceException

NullReferenceException używa COR_E_NULLREFERENCE HRESULT, który ma wartość 0x80004003.

Aby uzyskać listę początkowych wartości właściwości dla wystąpienia programu NullReferenceException, zobacz NullReferenceException konstruktory.

Obsługa wyjątku NullReferenceException w kodzie wydania

Zwykle lepiej jest unikać wartości NullReferenceException niż obsługiwać ją po jej wystąpieniu. Obsługa wyjątku może utrudnić konserwację i zrozumienie kodu, a czasami wprowadzać inne błędy. Wyjątek NullReferenceException jest często błędem niemożliwym do odzyskania. W takich przypadkach zezwolenie na zatrzymanie wyjątku aplikacji może być najlepszą alternatywą.

Istnieje jednak wiele sytuacji, w których obsługa błędu może być przydatna:

  • Aplikacja może ignorować obiekty o wartości null. Jeśli na przykład aplikacja pobiera rekordy i przetwarza je w bazie danych, może być możliwe zignorowanie pewnej liczby nieprawidłowych rekordów, które powodują wystąpienie obiektów o wartości null. Rejestrowanie nieprawidłowych danych w pliku dziennika lub w interfejsie użytkownika aplikacji może być wszystko, co musisz zrobić.

  • Możesz odzyskać dane z wyjątku. Na przykład wywołanie usługi internetowej zwracającej typ odwołania może zwracać wartość null, jeśli połączenie zostanie utracone lub przekroczono limit czasu połączenia. Możesz spróbować ponownie opublikować połączenie i spróbować ponownie nawiązać połączenie.

  • Stan aplikacji można przywrócić do prawidłowego stanu. Na przykład można wykonać wieloetapowe zadanie, które wymaga zapisania informacji w magazynie danych przed wywołaniem metody, która zgłasza wyjątek NullReferenceException. Jeśli niezainicjowany obiekt uszkodzi rekord danych, możesz usunąć poprzednie dane przed zamknięciem aplikacji.

  • Chcesz zgłosić wyjątek. Jeśli na przykład błąd został spowodowany błędem od użytkownika aplikacji, możesz wygenerować komunikat, aby pomóc im podać poprawne informacje. Możesz również rejestrować informacje o błędzie, aby ułatwić rozwiązanie problemu. Niektóre struktury, takie jak ASP.NET, mają procedurę obsługi wyjątków wysokiego poziomu, która przechwytuje wszystkie błędy, których aplikacja nigdy nie ulega awarii; w takim przypadku rejestrowanie wyjątku może być jedynym sposobem, w jaki można wiedzieć, że występuje.

Konstruktory

NullReferenceException()

Inicjuje nowe wystąpienie NullReferenceException klasy, ustawiając Message właściwość nowego wystąpienia na komunikat dostarczony przez system, który opisuje błąd, taki jak "Wartość null" została znaleziona, gdzie wymagane było wystąpienie obiektu. Ten komunikat uwzględnia bieżącą kulturę systemu.

NullReferenceException(SerializationInfo, StreamingContext)
Przestarzałe.

Inicjuje nowe wystąpienie klasy NullReferenceException z zserializowanymi danymi.

NullReferenceException(String)

Inicjuje NullReferenceException nowe wystąpienie klasy z określonym komunikatem o błędzie.

NullReferenceException(String, Exception)

Inicjuje nowe wystąpienie NullReferenceException klasy z określonym komunikatem o błędzie i odwołaniem do wewnętrznego wyjątku, który jest przyczyną tego wyjątku.

Właściwości

Data

Pobiera kolekcję par klucz/wartość, które zapewniają dodatkowe informacje zdefiniowane przez użytkownika dotyczące wyjątku.

(Odziedziczone po Exception)
HelpLink

Pobiera lub ustawia link do pliku pomocy skojarzonego z tym wyjątkiem.

(Odziedziczone po Exception)
HResult

Pobiera lub ustawia HRESULT, zakodowaną wartość liczbową przypisaną do określonego wyjątku.

(Odziedziczone po Exception)
InnerException

Exception Pobiera wystąpienie, które spowodowało bieżący wyjątek.

(Odziedziczone po Exception)
Message

Pobiera komunikat opisujący bieżący wyjątek.

(Odziedziczone po Exception)
Source

Pobiera lub ustawia nazwę aplikacji lub obiektu, który powoduje błąd.

(Odziedziczone po Exception)
StackTrace

Pobiera reprezentację ciągu natychmiastowych ramek w stosie wywołań.

(Odziedziczone po Exception)
TargetSite

Pobiera metodę, która zgłasza bieżący wyjątek.

(Odziedziczone po Exception)

Metody

Equals(Object)

Określa, czy dany obiekt jest taki sam, jak bieżący obiekt.

(Odziedziczone po Object)
GetBaseException()

W przypadku zastąpienia w klasie pochodnej zwraca Exception główną przyczynę co najmniej jednego kolejnego wyjątku.

(Odziedziczone po Exception)
GetHashCode()

Służy jako domyślna funkcja skrótu.

(Odziedziczone po Object)
GetObjectData(SerializationInfo, StreamingContext)
Przestarzałe.

Po przesłonięciu w klasie pochodnej ustawia SerializationInfo wartość z informacjami o wyjątku.

(Odziedziczone po Exception)
GetType()

Pobiera typ środowiska uruchomieniowego bieżącego wystąpienia.

(Odziedziczone po Exception)
MemberwiseClone()

Tworzy płytkią kopię bieżącego Objectelementu .

(Odziedziczone po Object)
ToString()

Tworzy i zwraca reprezentację ciągu bieżącego wyjątku.

(Odziedziczone po Exception)

Zdarzenia

SerializeObjectState
Przestarzałe.

Występuje, gdy wyjątek jest serializowany w celu utworzenia obiektu stanu wyjątku zawierającego serializowane dane o wyjątku.

(Odziedziczone po Exception)

Dotyczy

Zobacz też