NullReferenceException NullReferenceException NullReferenceException NullReferenceException Class

定义

尝试取消引用空对象引用时引发的异常。The exception that is thrown when there is an attempt to dereference a null object reference.

public ref class NullReferenceException : SystemException
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public class NullReferenceException : SystemException
type NullReferenceException = class
    inherit SystemException
Public Class NullReferenceException
Inherits SystemException
继承
NullReferenceExceptionNullReferenceExceptionNullReferenceExceptionNullReferenceException
属性

注解

一个NullReferenceException当你尝试访问上一个其值为的类型的成员时引发异常nullA NullReferenceException exception is thrown when you try to access a member on a type whose value is null. 一个NullReferenceException异常通常反映了开发人员错误,并在以下情况下引发:A NullReferenceException exception typically reflects developer error and is thrown in the following scenarios:

  • 忘记了实例化一个引用类型。You've forgotten to instantiate a reference type. 在以下示例中,names已声明,但决不实例化: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()
    

    它们编译此代码时,某些编译器将发出警告。Some compilers issue a warning when they compile this code. 其他人发出一个错误,且编译将失败。Others issue an error, and the compilation fails. 若要解决此问题,实例化对象,以便其值不再nullTo address this problem, instantiate the object so that its value is no longer null. 下面的示例通过调用类型的类构造函数执行此操作。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
    
  • 忘记了在初始化之前维度数组中。You've forgotten to dimension an array before initializing it. 在以下示例中,values被声明为一个整数数组,但永远不会指定它所包含的元素数。In the following example, values is declared to be an integer array, but the number of elements that it contains is never specified. 初始化因此引发其值的尝试NullReferenceException异常。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()
    

    可以通过在进行初始化之前声明的数组中的元素数,如以下示例来消除此异常。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
    

    声明和初始化数组的详细信息,请参阅数组数组For more information on declaring and initializing arrays, see Arrays and Arrays.

  • 您获得null从一种方法,返回值,然后在返回的类型上调用方法。You get a null return value from a method, and then call a method on the returned type. 这有时是因文档错误;请注意,方法调用可以返回文档失败nullThis sometimes is the result of a documentation error; the documentation fails to note that a method call can return null. 在其他情况下,您的代码错误地假定,该方法将始终返回一个非null值。In other cases, your code erroneously assumes that the method will always return a non-null value.

    在下面的示例代码假定Array.Find方法始终返回Person对象,其FirstName字段匹配的搜索字符串。The code in the following example assumes that the Array.Find method always returns Person object whose FirstName field matches a search string. 由于没有任何匹配项,则运行时会引发NullReferenceException异常。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()
    

    若要解决此问题,测试方法的返回值,以确保它不是null之前调用的任何成员,如以下示例所示。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
    
  • 使用表达式 (例如,要链接列表的方法或属性一起) 来检索一个值,尽管您检查值是否null,运行时仍会引发NullReferenceException异常。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. 这是因为在表达式中的中间值之一返回nullThis occurs because one of the intermediate values in the expression returns null. 因此,使测试null从不会进行计算。As a result, your test for null is never evaluated.

    下面的示例定义Pages缓存 web 页,对它们进行介绍的有关信息的对象Page对象。The following example defines a Pages object that caches information about web pages, which are presented by Page objects. Example.Main方法检查是否在当前网页具有非 null 标题,如果是这样,显示的标题。The Example.Main method checks whether the current web page has a non-null title and, if it does, displays the title. 尽管此检查,但是,该方法将引发NullReferenceException异常。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()
    

    因为引发异常pages.CurrentPage返回null如果没有页面信息存储在缓存中。The exception is thrown because pages.CurrentPage returns null if no page information is stored in the cache. 此异常可以更正通过测试的值CurrentPage属性检索当前之前Page对象的Title属性,作为下面的示例执行: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.
    
  • 在枚举的元素的数组,其中包含引用类型,并到一个元素引发的进程在尝试NullReferenceException异常。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.

    下面的示例定义一个字符串数组。The following example defines a string array. 一个for语句枚举中数组的元素,并调用每个字符串Trim方法,然后再显示字符串。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()
    

    如果你假定数组的每个元素必须包含一个非 null 值,并且数组元素的值确实是会发生此异常nullThis 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. 可通过测试中的元素是否是消除异常null在执行之前对该元素的任何操作,如以下示例所示。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
    
  • 一个NullReferenceException传递的方法引发异常nullA NullReferenceException exception is thrown by a method that is passed null. 某些方法验证传递给它们的参数。Some methods validate the arguments that are passed to them. 如果它们执行操作,并且其中一个参数是null,该方法将引发System.ArgumentNullException异常。If they do and one of the arguments is null, the method throws an System.ArgumentNullException exception. 否则,它会引发NullReferenceException异常。Otherwise, it throws a NullReferenceException exception. 下面的示例演示了此方案。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()
    

    若要解决此问题,请确保传递给该方法的参数不是null,或处理中引发的异常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. 有关更多信息,请参见 异常中定义的接口的私有 C++ 特定实现。For more information, see Exceptions.

以下 Microsoft 中间语言 (MSIL) 指令会引发NullReferenceException: callvirtcpblkcpobjinitblkldelem.<type>ldelemaldfldldfldaldind.<type>``ldlenstelem.<type>stfldstind.<type>throw,并unboxThe 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 使用 HRESULT COR_E_NULLREFERENCE,其值 0x80004003。NullReferenceException uses the HRESULT COR_E_NULLREFERENCE, which has the value 0x80004003.

有关实例的初始属性值的列表NullReferenceException,请参阅NullReferenceException构造函数。For a list of initial property values for an instance of NullReferenceException, see the NullReferenceException constructors.

处理发行代码中的 NullReferenceExceptionHandling NullReferenceException in release code

通常,最好避免 NullReferenceException 比以处理在其后发生。It's usually better to avoid a NullReferenceException than to handle it after it occurs. 处理异常会导致代码更难维护和理解,并且有时会引入其他 bug。Handling an exception can make your code harder to maintain and understand, and can sometimes introduce other bugs. NullReferenceException 通常为不可恢复的错误。A NullReferenceException is often a non-recoverable error. 在这些情况下,让异常停止应用可能是最佳替代方法。In these cases, letting the exception stop the app might be the best alternative.

然而,在许多情况下,处理错误可能非常有用:However, there are many situations where handling the error can be useful:

  • 你的应用可以忽略为 null 的对象。Your app can ignore objects that are null. 例如,如果你的应用检索并处理数据库中的记录,则你可以忽略一些导致 null 对象的错误记录。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. 你可能仅需在日志文件或应用程序 UI 中记录错误数据。Recording the bad data in a log file or in the application UI might be all you have to do.

  • 可以从异常中恢复。You can recover from the exception. 例如,在连接丢失或连接超时的情况下,对返回引用类型的 Web 服务的调用可能会返回 null。可尝试重新建立连接并再次尝试调用。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.

  • 可将你的应用状态还原到有效状态。You can restore the state of your app to a valid state. 例如,你可能要执行多步骤的任务,该任务需要你在调用引发 NullReferenceException 的方法之前将信息保存到数据存储。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. 如果未初始化的对象可能会损坏数据记录,你可以在关闭应用之前删除之前的数据。If the uninitialized object would corrupt the data record, you can remove the previous data before you close the app.

  • 你需要报告异常。You want to report the exception. 例如,如果该错误由应用用户的某个错误引起,你可以生成一条可帮助该用户提供正确信息的消息。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. 你还可以记录有关该错误的信息来帮助你解决此问题。You can also log information about the error to help you fix the problem. 某些框架(如 ASP.NET)具有高级别的异常处理程序,该处理程序可捕获所有错误,以便应用永远不会发生崩溃,在这种情况下,记录异常可能是你用来了解是否发生异常的唯一方式。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.

构造函数

NullReferenceException() NullReferenceException() NullReferenceException() NullReferenceException()

初始化 NullReferenceException 类的新实例,将新实例的 Message 属性设置为系统提供的描述错误的消息,如“在需要对象实例的地方找到了值‘null’。”。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." 此消息将当前系统区域性考虑在内。This message takes into account the current system culture.

NullReferenceException(SerializationInfo, StreamingContext) NullReferenceException(SerializationInfo, StreamingContext) NullReferenceException(SerializationInfo, StreamingContext) NullReferenceException(SerializationInfo, StreamingContext)

用序列化数据初始化 NullReferenceException 类的新实例。Initializes a new instance of the NullReferenceException class with serialized data.

NullReferenceException(String) NullReferenceException(String) NullReferenceException(String) NullReferenceException(String)

用指定的错误消息初始化 NullReferenceException 类的新实例。Initializes a new instance of the NullReferenceException class with a specified error message.

NullReferenceException(String, Exception) NullReferenceException(String, Exception) NullReferenceException(String, Exception) NullReferenceException(String, Exception)

使用指定的错误消息和对作为此异常原因的内部异常的引用来初始化 NullReferenceException 类的新实例。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.

属性

Data Data Data Data

获取提供有关异常的其他用户定义信息的键/值对集合。Gets a collection of key/value pairs that provide additional user-defined information about the exception.

(Inherited from Exception)
HelpLink HelpLink HelpLink HelpLink

获取或设置指向与此异常关联的帮助文件链接。Gets or sets a link to the help file associated with this exception.

(Inherited from Exception)
HResult HResult HResult HResult

获取或设置 HRESULT(一个分配给特定异常的编码数字值)。Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.

(Inherited from Exception)
InnerException InnerException InnerException InnerException

获取导致当前异常的 Exception 实例。Gets the Exception instance that caused the current exception.

(Inherited from Exception)
Message Message Message Message

获取描述当前异常的消息。Gets a message that describes the current exception.

(Inherited from Exception)
Source Source Source Source

获取或设置导致错误的应用程序或对象的名称。Gets or sets the name of the application or the object that causes the error.

(Inherited from Exception)
StackTrace StackTrace StackTrace StackTrace

获取调用堆栈上的即时框架字符串表示形式。Gets a string representation of the immediate frames on the call stack.

(Inherited from Exception)
TargetSite TargetSite TargetSite TargetSite

获取引发当前异常的方法。Gets the method that throws the current exception.

(Inherited from Exception)

方法

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetBaseException() GetBaseException() GetBaseException() GetBaseException()

当在派生类中重写时,返回 Exception,它是一个或多个并发的异常的根源。When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.

(Inherited from Exception)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(Inherited from Object)
GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext)

当在派生类中重写时,用关于异常的信息设置 SerializationInfoWhen overridden in a derived class, sets the SerializationInfo with information about the exception.

(Inherited from Exception)
GetType() GetType() GetType() GetType()

获取当前实例的运行时类型。Gets the runtime type of the current instance.

(Inherited from Exception)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

创建并返回当前异常的字符串表示形式。Creates and returns a string representation of the current exception.

(Inherited from Exception)

事件

SerializeObjectState SerializeObjectState SerializeObjectState SerializeObjectState

当异常被序列化用来创建包含有关该异常的徐列出数据的异常状态对象时会出现该问题。Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception.

(Inherited from Exception)

适用于

另请参阅