NullReferenceException Osztály

Definíció

A null objektumhivatkozások elhalasztására tett kísérlet során megjelenő kivétel.

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
Öröklődés
NullReferenceException
Öröklődés
NullReferenceException
Attribútumok

Megjegyzések

Kivételt NullReferenceException eredményez, ha egy olyan taghoz próbál hozzáférni, amelynek értéke a nullkövetkező. A NullReferenceException kivétel általában a fejlesztői hibát tükrözi, és a következő forgatókönyvekben jelenik meg:

Note

A C# legtöbb NullReferenceException kivételét elkerülheti a null-feltételes operátor (?.) vagy a null-szenesítő operátor (??) használatával. További információért tekintse meg: Null értékű hivatkozástípusok. Az alábbi C#-példák feltételezik, hogy a null értékű környezet le van tiltva (nem ajánlott).

  • Elfelejtette példányosítani a referenciatípust. A következő példában deklarálva van, names de soha nem történik példányosítás (az érintett sort a C#-példában fűzi hozzá a program, mivel nem fordítja le):

    using System.Collections.Generic;
    
    public class UseBeforeAssignExample
    {
        public static void Main(string[] args)
        {
            int value = int.Parse(args[0]);
            List<string> names;
            if (value > 0)
                names = [];
    
            //names.Add("Major Major Major");
        }
    }
    
    // Compilation displays a warning like the following:
    //    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 UseBeforeAssignExample.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()
    

    Egyes fordítók figyelmeztetést adnak ki a kód lefordításakor. Mások hibát adnak ki, és a fordítás meghiúsul. A probléma megoldásához példányosíthatja az objektumot, hogy az értéke ne legyen többé null. Az alábbi példa egy típus osztálykonstruktorának meghívásával teszi ezt.

    using System.Collections.Generic;
    
    public class AnotherExample
    {
        public static void Main()
        {
            List<string> names = ["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
    
  • Az inicializálás előtt elfelejtette méretezni a tömböt. Az alábbi példában values egész számtömbnek van deklarálva, de a benne található elemek száma soha nem lesz megadva. Az értékek inicializálására tett kísérlet ezért kivételt NullReferenceException eredményez.

    int[] values = null;
    for (int ctr = 0; ctr <= 9; ctr++)
        values[ctr] = ctr * 2;
    
    foreach (int 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 Array3Example.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()
    

    A kivétel megszüntetéséhez deklarálhatja a tömb elemeinek számát az inicializálás előtt, ahogyan az alábbi példa is szemlélteti.

    int[] values = new int[10];
    for (int ctr = 0; ctr <= 9; ctr++)
        values[ctr] = ctr * 2;
    
    foreach (int 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
    

    A tömbök deklarálásával és inicializálásával kapcsolatos további információkért lásd: Tömbök és tömbök.

  • Null visszatérési értéket kap egy metódustól, majd meghív egy metódust a visszaadott típuson. Ez néha egy dokumentációs hiba eredménye; a dokumentáció nem veszi figyelembe, hogy egy metódushívás vissza tud térni null. Más esetekben a kód hibásan feltételezi, hogy a metódus mindig nem null értéket ad vissza.

    Az alábbi példában szereplő kód feltételezi, hogy a Array.Find metódus mindig olyan objektumot ad Person vissza, amelynek FirstName a mezője megfelel egy keresési sztringnek. Mivel nincs egyezés, a futtatókörnyezet kivételt NullReferenceException jelez.

    public static void NoCheckExample()
    {
        Person[] persons = Person.AddRange([ "Abigail", "Abra",
                                          "Abraham", "Adrian", "Ariella",
                                          "Arnold", "Aston", "Astor" ]);
        string nameToFind = "Robert";
        Person found = Array.Find(persons, p => p.FirstName == nameToFind);
        Console.WriteLine(found.FirstName);
    }
    
    // The example displays the following output:
    //       Unhandled Exception: System.NullReferenceException:
    //       Object reference not set to an instance of an object.
    
    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()
    

    A probléma megoldásához tesztelje a metódus visszatérési értékét, és győződjön meg arról, hogy még nem null hívja meg egyik tagját sem, ahogy az alábbi példa is szemlélteti.

    public static void ExampleWithNullCheck()
    {
        Person[] persons = Person.AddRange([ "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($"'{nameToFind}' not found.");
    }
    
    // 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
    
  • Egy kifejezést használ (például a metódusok vagy tulajdonságok listáját összeláncolva) egy érték lekéréséhez, és bár ellenőrzi, hogy az érték valóban igaz-e null, a futtatókörnyezet továbbra is kivételt NullReferenceException jelez. Ez azért fordul elő, mert a kifejezés egyik köztes értéke ad vissza null. Ennek eredményeképpen a teszt null soha nem lesz kiértékelve.

    Az alábbi példa egy Pages olyan objektumot határoz meg, amely gyorsítótárazza a weblapokra vonatkozó információkat, amelyeket az objektumok mutatnak be Page . A Example.Main metódus ellenőrzi, hogy az aktuális weblap címe nem null értékű-e, és ha igen, megjeleníti-e a címet. Az ellenőrzés ellenére azonban a metódus kivételt NullReferenceException eredményez.

    public class Chain1Example
    {
        public static void Main()
        {
            var pages = new Pages();
            if (!string.IsNullOrEmpty(pages.CurrentPage.Title))
            {
                string title = pages.CurrentPage.Title;
                Console.WriteLine($"Current title: '{title}'");
            }
        }
    }
    
    public class Pages
    {
        readonly 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] is 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 Chain1Example.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()
    

    A kivétel azért van kiadva, mert pages.CurrentPage akkor ad vissza null , ha a gyorsítótárban nincsenek lapinformációk. Ezt a kivételt úgy lehet kijavítani, hogy teszteli a tulajdonság értékét az CurrentPage aktuális Page objektum tulajdonságának beolvasása Title előtt, ahogyan az alábbi példa is teszi:

    var pages = new Pages();
    Page current = pages.CurrentPage;
    if (current != null)
    {
        string title = current.Title;
        Console.WriteLine($"Current title: '{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.
    
  • Egy hivatkozástípusokat tartalmazó tömb elemeit számba kell vennie, és az egyik elem feldolgozására tett kísérlet kivételt NullReferenceException eredményez.

    Az alábbi példa egy sztringtömböt határoz meg. Az for utasítás számba adja a tömb elemeit, és meghívja az egyes sztringek metódusát Trim a sztring megjelenítése előtt.

    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.
    
    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()
    

    Ez a kivétel akkor fordul elő, ha feltételezi, hogy a tömb minden elemének nem null értéket kell tartalmaznia, és a tömbelem értéke valójában null. A kivétel kiküszöbölhető, ha teszteli, hogy az elem az adott elemen végzett bármilyen művelet végrehajtása előtt van-e null , ahogyan az az alábbi példában látható.

    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
    
  • Egy metódus, amikor az egyik argumentumának egy tagját éri el, de ez az argumentum a .null A PopulateNames következő példában szereplő metódus a kivételt a sorra names.Add(arrName);veti.

    using System.Collections.Generic;
    
    public class NRE2Example
    {
        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 (string 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 NRE2Example.PopulateNames(List`1 names)
    //       at NRE2Example.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()
    

    A probléma megoldásához győződjön meg arról, hogy a metódusnak átadott argumentum nem nullaz, vagy kezelje a blokkban kidobott kivételt try…catch…finally . További információ: Kivételek.

  • A lista a típus ismerete nélkül jön létre, és a lista inicializálása nem történt meg. A GetList következő példában szereplő metódus a kivételt a sorra emptyList.Add(value)veti.

    using System;
    using System.Collections.Generic;
    using System.Collections;
    using System.Runtime.Serialization;
    
    public class NullReferenceExample
    {
        public static void Main()
        {
            var listType = GetListType();
            _ = GetList(listType);
        }
    
        private static Type GetListType()
        {
            return typeof(List<int>);
        }
    
        private static IList GetList(Type type)
        {
            var emptyList = (IList)FormatterServices.GetUninitializedObject(type); // Does not call list constructor
            var value = 1;
            emptyList.Add(value);
            return emptyList;
        }
    }
    // The example displays output like the following:
    //    Unhandled Exception: System.NullReferenceException: 'Object reference
    //    not set to an instance of an object.'
    //    at System.Collections.Generic.List`1.System.Collections.IList.Add(Object item)
    //    at NullReferenceExample.GetList(Type type): line 24
    

    A probléma megoldásához győződjön meg arról, hogy a lista inicializálva van (ennek egyik módja a hívás Activator.CreateInstance ahelyett FormatterServices.GetUninitializedObject), hogy kezelje a blokkok try…catch…finally kidobott kivételét. További információ: Kivételek.

A következő Microsoft köztes nyelv (MSIL) utasításai NullReferenceException: callvirt, cpblk, cpobj, initblk, ldelem.<type>, ldelema, ldfld, ldflda, ldind.<type>, ldlen, stelem.<type>, stfld, stind.<type>, throw és unbox.

NullReferenceException A HRESULT COR_E_NULLREFERENCEfüggvényt használja, amelynek értéke 0x80004003.

A NullReferenceException példány kezdeti tulajdonságainak listájáért tekintse meg a NullReferenceException konstruktorokat.

Mikor kell kezelni a NullReferenceException kivételeket?

Általában jobb elkerülni a NullReferenceExceptiont, mint a bekövetkezése után kezelni. A kivétel kezelése megnehezítheti a kód karbantartását és megértését, és néha más hibákat is okozhat. A NullReferenceException gyakran nem helyreállítható hiba. Ezekben az esetekben a kivétel leállítása az alkalmazás leállítása lehet a legjobb alternatíva.

Számos esetben azonban hasznos lehet a hiba kezelése:

  • Az alkalmazás figyelmen kívül hagyhatja a null értékű objektumokat. Ha például az alkalmazás lekéri és feldolgozza a rekordokat egy adatbázisban, előfordulhat, hogy figyelmen kívül hagy néhány hibás rekordot, amelyek null objektumokat eredményeznek. A rossz adatok rögzítése egy naplófájlban vagy az alkalmazás felhasználói felületén lehet, hogy csak annyit kell tennie.

  • A kivételből helyreállhat. Egy hivatkozástípust visszaadó webszolgáltatás hívása például null értéket ad vissza, ha a kapcsolat megszakad, vagy a kapcsolat túllépi az időkorlátot. Megpróbálhatja újra létrehozni a kapcsolatot, és újra megpróbálhatja a hívást.

  • Az alkalmazás állapotát visszaállíthatja érvényes állapotra. Előfordulhat például, hogy többlépéses feladatot hajt végre, amely megköveteli, hogy adatokat mentsen egy adattárba, mielőtt meghív egy NullReferenceException metódust. Ha a nem inicializált objektum rontaná az adatrekordot, az alkalmazás bezárása előtt eltávolíthatja az előző adatokat.

  • Jelenteni szeretné a kivételt. Ha például a hibát az alkalmazás felhasználójának hibája okozta, létrehozhat egy üzenetet, amely segít nekik a megfelelő információk megadásában. A hiba adatait naplózhatja is, hogy segítsen a probléma megoldásában. Egyes keretrendszerek, például a ASP.NET, magas szintű kivételkezelővel rendelkeznek, amely rögzíti az alkalmazás által soha nem összeomlott összes hibát; ebben az esetben a kivétel naplózása lehet az egyetlen módja annak, hogy tudja, hogy ez történik.

Konstruktorok

Name Description
NullReferenceException()

Inicializálja az NullReferenceException osztály egy új példányát, és az Message új példány tulajdonságát egy rendszer által megadott üzenetre állítja, amely leírja a hibát, például"A null érték ott található, ahol egy objektumpéldányra volt szükség." Ez az üzenet figyelembe veszi a jelenlegi rendszerkultúrát.

NullReferenceException(SerializationInfo, StreamingContext)
Elavult.

Inicializálja az NullReferenceException osztály új példányát szerializált adatokkal.

NullReferenceException(String, Exception)

Inicializálja az NullReferenceException osztály új példányát egy megadott hibaüzenettel és a kivétel okaként szolgáló belső kivételre mutató hivatkozással.

NullReferenceException(String)

Inicializálja az NullReferenceException osztály új példányát egy megadott hibaüzenettel.

Tulajdonságok

Name Description
Data

Lekéri a kulcs-/érték párok gyűjteményét, amelyek további, felhasználó által definiált információkat biztosítanak a kivételről.

(Öröklődés forrása Exception)
HelpLink

Lekéri vagy beállítja a kivételhez társított súgófájlra mutató hivatkozást.

(Öröklődés forrása Exception)
HResult

Lekéri vagy beállítja a HRESULT-ot, egy kódolt numerikus értéket, amely egy adott kivételhez van hozzárendelve.

(Öröklődés forrása Exception)
InnerException

Lekéri az Exception aktuális kivételt okozó példányt.

(Öröklődés forrása Exception)
Message

Az aktuális kivételt leíró üzenet jelenik meg.

(Öröklődés forrása Exception)
Source

Lekéri vagy beállítja az alkalmazás vagy a hibát okozó objektum nevét.

(Öröklődés forrása Exception)
StackTrace

Lekéri a hívásverem közvetlen kereteinek sztringképét.

(Öröklődés forrása Exception)
TargetSite

Lekéri az aktuális kivételt okozó metódust.

(Öröklődés forrása Exception)

Metódusok

Name Description
Equals(Object)

Meghatározza, hogy a megadott objektum egyenlő-e az aktuális objektummal.

(Öröklődés forrása Object)
GetBaseException()

Ha egy származtatott osztály felül van bírálva, egy Exception vagy több későbbi kivétel kiváltó okát adja vissza.

(Öröklődés forrása Exception)
GetHashCode()

Ez az alapértelmezett kivonatoló függvény.

(Öröklődés forrása Object)
GetObjectData(SerializationInfo, StreamingContext)
Elavult.

Ha felül van bírálva egy származtatott osztályban, a SerializationInfo kivétel adatait adja meg.

(Öröklődés forrása Exception)
GetType()

Lekéri az aktuális példány futtatókörnyezeti típusát.

(Öröklődés forrása Exception)
MemberwiseClone()

Az aktuális Objectpéldány sekély másolatát hozza létre.

(Öröklődés forrása Object)
ToString()

Létrehozza és visszaadja az aktuális kivétel sztring-ábrázolását.

(Öröklődés forrása Exception)

esemény

Name Description
SerializeObjectState
Elavult.

Akkor fordul elő, ha a kivétel szerializálva van egy kivételállapot-objektum létrehozásához, amely szerializált adatokat tartalmaz a kivételről.

(Öröklődés forrása Exception)

A következőre érvényes:

Lásd még