找到你要的答案

Q:What is a NullReferenceException, and how do I fix it? What is the cause? Debugging Examples Ways to Avoid NullReference Exception — Visual Basic

Q:NullReferenceException是什么,我怎么解决它? 原因是什么? 调试 实例 避免的方法 nullreference例外,Visual Basic

I have some code and when it executes, it throws a NullReferenceException, saying:

Object reference not set to an instance of an object.

What does this mean, and what can I do about it?

我有一些代码执行时,它抛出NullReferenceException,说:

对象引用未设置为对象实例。

这意味着什么,我能做些什么呢?

answer1: 回答1:

What is the cause?

Bottom Line

You are trying to use something that is null (or Nothing in VB.NET). This means you either set it to null, or you never set it to anything at all.

Like anything else, null gets passed around. If it is null in method "A", it could be that method "B" passed a null to method "A".

The rest of this article goes into more detail and shows mistakes that many programmers often make which can lead to a NullReferenceException.

More Specifically

The runtime throwing a NullReferenceException always means the same thing: you are trying to use a reference. The reference is not initialized (or it was initialized, but is no longer initialized).

This means the reference is null, and you cannot access members through a null reference. The simplest case:

string foo = null;
foo.ToUpper();

This will throw a NullReferenceException at the second line, because you can't call the instance method ToUpper() on a string reference pointing to null.

Debugging

How do you find the source of a NullReferenceException? Apart from looking at the exception itself, which will be thrown exactly at the location where it occurs, the general rules of debugging in Visual Studio apply: place strategic breakpoints and inspect your variables, either by hovering the mouse over their names, opening a (Quick)Watch window or using the various debugging panels like Locals and Autos.

If you want to find out where the reference is or isn't set, right-click its name and select "Find All References". You can then place a breakpoint at every found location and run your program with the debugger attached. Every time the debugger breaks on such a breakpoint, you need to determine whether you expect the reference to be non-null, inspect the variable and and verify that it points to an instance when you expect it to.

By following the program flow this way you can find the location where the instance should not be null, and why it isn't properly set.

Examples

Some common scenarios where the exception can be thrown:

Generic

ref1.ref2.ref3.member

If ref1 or ref2 or ref3 is null, then you'll get a NullReferenceException. If you want to solve the problem, then find out which one is null by rewriting the expression to its simpler equivalent:

var r1 = ref1;
var r2 = r1.ref2;
var r3 = r2.ref3;
r3.member

Specifically, in HttpContext.Current.User.Identity.Name, the HttpContext.Current could be null, or the User property could be null, or the Identity property could be null.

Indirect

public class Person {
    public int Age { get; set; }
}
public class Book {
    public Person Author { get; set; }
}
public class Example {
    public void Foo() {
        Book b1 = new Book();
        int authorAge = b1.Author.Age; // You never initialized the Author property.
                                       // there is no Person to get an Age from.
    }
}

If you want to avoid the child (Person) null reference you could initialize it in the parent (Book) object's constructor.

The same applies to nested object initializers:

Book b1 = new Book { Author = { Age = 45 } };

While the new keyword is used, it only creates a new instance of Book, but not a new instance of Person, so the Author the property is still null.

Array

int[] numbers = null;
int n = numbers[0]; // numbers is null. There is no array to index.

Array Elements

Person[] people = new Person[5];
people[0].Age = 20 // people[0] is null. The array was allocated but not
                   // initialized. There is no Person to set the Age for.

Jagged Arrays

long[][] array = new long[1][];
array[0][0] = 3; // is null because only the first dimension is yet initialized.
                 // Use array[0] = new long[2]; first.

Collection/List/Dictionary

Dictionary<string, int> agesForNames = null;
int age = agesForNames["Bob"]; // agesForNames is null.
                               // There is no Dictionary to perform the lookup.

Range Variable (Indirect/Deferred)

public class Person {
    public string Name { get; set; }
}
var people = new List<Person>();
people.Add(null);
var names = from p in people select p.Name;
string firstName = names.First(); // Exception is thrown here, but actually occurs
                                  // on the line above.  "p" is null because the
                                  // first element we added to the list is null.

Events

public class Demo
{
    public event EventHandler StateChanged;

    protected virtual void OnStateChanged(EventArgs e)
    {        
        StateChanged(this, e); // Exception is thrown here 
                               // if no event handlers have been attached
                               // to StateChanged event
    }
}

Bad Naming Conventions:

If you named fields differently from locals, you might have realized that you never initialized the field.

public class Form1 {
    private Customer customer;

    private void Form1_Load(object sender, EventArgs e) {
        Customer customer = new Customer();
        customer.Name = "John";
    }

    private void Button_Click(object sender, EventArgs e) {
        MessageBox.Show(customer.Name);
    }
}

This can be solved by following the convention to prefix fields with an underscore:

private Customer _customer;

ASP.NET Page Life cycle:

public partial class Issues_Edit : System.Web.UI.Page
{
    protected TestIssue myIssue;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // Only called on first load, not when button clicked
            myIssue = new TestIssue(); 
        }
    }

    protected void SaveButton_Click(object sender, EventArgs e)
    {
        myIssue.Entry = "NullReferenceException here!";
    }
}

ASP.NET Session Values

// if the "FirstName" session value has not yet been set,
// then this line will throw a NullReferenceException
string firstName = Session["FirstName"].ToString();

ASP.NET MVC empty view models

If the exception occurs when referencing a property of @Model in an ASP.NET MVC view, you need to understand that the Model gets set in your action method, when you return a view. When you return an empty model (or model property) from your controller, the exception occurs when the views accesses it:

// Controller
public class Restaurant:Controller
{
    public ActionResult Search()
    {
         return View();  // Forgot the provide a Model here.
    }
}

// Razor view 
@foreach (var restaurantSearch in Model.RestaurantSearch)  // Throws.
{
}

<p>@Model.somePropertyName</p> <!-- Also throws -->

WPF Control Creation Order and Events

WPF controls are created during the call to InitializeComponent in the order they appear in the visual tree. A NullReferenceException will be raised in the case of early-created controls with event handlers, etc, that fire during InitializeComponent which reference late-created controls.

For example :

<Grid>
    <!-- Combobox declared first -->
    <ComboBox Name="comboBox1" 
              Margin="10"
              SelectedIndex="0" 
              SelectionChanged="comboBox1_SelectionChanged">
        <ComboBoxItem Content="Item 1" />
        <ComboBoxItem Content="Item 2" />
        <ComboBoxItem Content="Item 3" />
    </ComboBox>

    <!-- Label declared later -->
    <Label Name="label1" 
           Content="Label"
           Margin="10" />
</Grid>

Here comboBox1 is created before label1. If comboBox1_SelectionChanged attempts to reference label1 it will not yet have been created.

private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    label1.Content = comboBox1.SelectedIndex.ToString(); // NullReference here!!
}

Changing the order of the declarations in the XAML (ie: listing label1 before comboBox1, ignoring issues of design philosophy, would at least resolve the NullReferenceException here.

Cast with as

var myThing = someObject as Thing;

This doesn't throw an InvalidCastException, but returns a null when the cast fails (and when someObject is itself null). So be aware of that.

LINQ FirstOrDefault() and SingleOrDefault()

The plain versions First() and Single() throw exceptions when there is nothing. The "OrDefault" versions return null in that case. So be aware of that.

foreach

foreach throws when you try to iterate null collection. Usually caused by unexpected null result from methods that return collections.

 List<int> list = null;    
 foreach(var v in list) { } // exception

More realistic example - select nodes from XML document. Will throw if nodes are not found but initial debugging shows that all properties valid:

 foreach (var node in myData.MyXml.DocumentNode.SelectNodes("//Data"))

Ways to Avoid

Explicitly check for null, and ignore null values.

If you expect the reference sometimes to be null, you can check for it being null before accessing instance members:

void PrintName(Person p) {
    if (p != null) {
        Console.WriteLine(p.Name);
    }
}

Explicitly check for null, and provide a default value.

Methods calls you expect to return an instance can return null, for example when the object being sought cannot be found. You can choose to return a default value when this is the case:

string GetCategory(Book b) {
    if (b == null)
        return "Unknown";
    return b.Category;
}

Explicitly check for null from method calls and throw a custom exception.

You can also throw a custom exception, only to catch it in the calling code:

string GetCategory(string bookTitle) {
    var book = library.FindBook(bookTitle);  // This may return null
    if (book == null)
        throw new BookNotFoundException(bookTitle);  // Your custom exception
    return book.Category;
}

Use Debug.Assert if a value should never be null, to catch the problem earlier than the exception occurs.

When you know during development that a method maybe can, but actually never should return null, you can use Debug.Assert() to break as soon as possible when it does occur:

string GetTitle(int knownBookID) {
    // You know this should never return null.
    var book = library.GetBook(knownBookID);  

    // Exception will occur on the next line instead of at the end of this method.
    Debug.Assert(book != null, "Library didn't return a book for known book ID.");

    // Some other code ...

    return book.Title; // Will never throw NullReferenceException in Debug mode.
}

Though this check will not end up in your release build, causing it to throw the NullReferenceException again when book == null at runtime in release mode.

Use GetValueOrDefault() for nullable value types to provide a default value when they are null.

DateTime? appointment = null;
Console.WriteLine(appointment.GetValueOrDefault(DateTime.Now));
// Will display the default value provided (DateTime.Now), because appointment is null.

appointment = new DateTime(2022, 10, 20);
Console.WriteLine(appointment.GetValueOrDefault(DateTime.Now));
// Will display the appointment date, not the default

Use the null coalescing operator: ?? [C#] or If() [VB].

The shorthand to providing a default value when a null is encountered:

IService CreateService(ILogger log, Int32? frobPowerLevel)
{
    var serviceImpl = new MyService(log ?? NullLog.Instance);

    // Note that the above "GetValueOrDefault()" can also be rewritten to use
    // the coalesce operator:
    serviceImpl.FrobPowerLevel = frobPowerLevel ?? 5;
}

Use the null condition operator: ?. (available in C# 6 and VB.NET 14):

This is also sometimes called the safe navigation or Elvis (after its shape) operator. If the expression on the left side of the operator is null, then the right side will not be evaluated and null is returned instead. That means cases like this:

var title = person.Title.ToUpper();

If the person does not have a title, this will throw an exception because it is trying to call ToUpper on a property with a null value.

In C# 5 and below, this can be guarded with:

var title = person.Title == null ? null : person.Title.ToUpper();

Now the title variable will be null instead of throwing an exception. C# 6 introduces a shorter syntax for this:

var title = person.Title?.ToUpper();

This will result in the title variable being null, and the call to ToUpper is not made if person.Title is null.

Of course, you still have to check title for null or use the null condition operator together with the null coalescing operator (??) to supply a default value:

// regular null check
int titleLength = 0;
if (title != null)
    titleLength = title.Length; // If title is null, this would throw NullReferenceException

// combining the `?` and the `??` operator
int titleLength = title?.Length ?? 0;

原因是什么?

Bottom Line

你正在使用的东西是空的(或VB。NET没有)。这意味着你要么将它设置为NULL,要么你根本就没有设置它。

像其他任何东西一样,空传。如果方法“a”中为NULL,则该方法“b”通过NULL方法“a”。

本文的其余部分将详细讨论和说明的错误,很多程序员经常导致NullReferenceException。

More Specifically

运行时抛出NullReferenceException总是意味着同样的事情:你正在使用一个参考。引用未初始化(或已初始化,但不再初始化)。

这意味着引用是空的,不能通过空引用访问成员。最简单情况:

string foo = null;
foo.ToUpper();

这将抛出NullReferenceException在第二线,因为你不能要求一个字符串的引用指向空的实例方法toupper()。

调试

你怎么找到NullReferenceException的来源?除了看异常本身,这将被完全在它发生的位置,调试在Visual Studio中应用的一般规律:地方战略断点你的变量和检查,无论是在他们的名字的鼠标,打开一个(快速)观察窗或使用各种调试板像当地人和汽车。

如果要查找引用是或未设置的,请右击其名称,然后选择“查找所有引用”。然后,您可以在每个找到的位置放置断点,并与调试器连接运行程序。每次调试器在这样的断点上断开时,您需要确定您是否希望引用是非空的,检查变量,并验证它在您希望。

通过这样的程序流,你可以找到实例不应该是NULL的位置,以及为什么它不能被正确设置。

实例

一些常见的情况下,可以抛出异常:

Generic

ref1.ref2.ref3.member

如果Ref1或ref2或REF3是空的,然后你会得到NullReferenceException。如果你想解决这个问题,那么通过重写表达式到它的简单等价,找出哪个是空的:

var r1 = ref1;
var r2 = r1.ref2;
var r3 = r2.ref3;
r3.member

具体来说,在httpcontext.current.user.identity.name,HttpContext。电流可以为空,或者用户属性可以为空,或标识属性的可空。

Indirect

public class Person {
    public int Age { get; set; }
}
public class Book {
    public Person Author { get; set; }
}
public class Example {
    public void Foo() {
        Book b1 = new Book();
        int authorAge = b1.Author.Age; // You never initialized the Author property.
                                       // there is no Person to get an Age from.
    }
}

如果要避免子(人)空引用,可以在父(书)对象的构造函数中初始化它。

这同样适用于嵌套的对象初始化器:

Book b1 = new Book { Author = { Age = 45 } };

当使用新关键字时,它只创建一个新的实例,但不是一个新的实例,所以作者的属性仍然是空的。

Array

int[] numbers = null;
int n = numbers[0]; // numbers is null. There is no array to index.

Array Elements

Person[] people = new Person[5];
people[0].Age = 20 // people[0] is null. The array was allocated but not
                   // initialized. There is no Person to set the Age for.

Jagged Arrays

long[][] array = new long[1][];
array[0][0] = 3; // is null because only the first dimension is yet initialized.
                 // Use array[0] = new long[2]; first.

Collection/List/Dictionary

Dictionary<string, int> agesForNames = null;
int age = agesForNames["Bob"]; // agesForNames is null.
                               // There is no Dictionary to perform the lookup.

Range Variable (Indirect/Deferred)

public class Person {
    public string Name { get; set; }
}
var people = new List<Person>();
people.Add(null);
var names = from p in people select p.Name;
string firstName = names.First(); // Exception is thrown here, but actually occurs
                                  // on the line above.  "p" is null because the
                                  // first element we added to the list is null.

Events

public class Demo
{
    public event EventHandler StateChanged;

    protected virtual void OnStateChanged(EventArgs e)
    {        
        StateChanged(this, e); // Exception is thrown here 
                               // if no event handlers have been attached
                               // to StateChanged event
    }
}

Bad Naming Conventions:

如果您命名字段与本地不同,您可能已经意识到您从未初始化字段。

public class Form1 {
    private Customer customer;

    private void Form1_Load(object sender, EventArgs e) {
        Customer customer = new Customer();
        customer.Name = "John";
    }

    private void Button_Click(object sender, EventArgs e) {
        MessageBox.Show(customer.Name);
    }
}

这可以通过遵循带前缀的前缀字段来解决:

private Customer _customer;

ASP.NET Page Life cycle:

public partial class Issues_Edit : System.Web.UI.Page
{
    protected TestIssue myIssue;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // Only called on first load, not when button clicked
            myIssue = new TestIssue(); 
        }
    }

    protected void SaveButton_Click(object sender, EventArgs e)
    {
        myIssue.Entry = "NullReferenceException here!";
    }
}

ASP.NET Session Values

// if the "FirstName" session value has not yet been set,
// then this line will throw a NullReferenceException
string firstName = Session["FirstName"].ToString();

ASP.NET MVC empty view models

如果异常发生时,参考“模型的属性在ASP.NET MVC视图,你需要理解的模型被设置在动作方法返回一个视图时,你。当从控制器返回空模型(或模型属性)时,异常会发生在视图访问它时:

// Controller
public class Restaurant:Controller
{
    public ActionResult Search()
    {
         return View();  // Forgot the provide a Model here.
    }
}

// Razor view 
@foreach (var restaurantSearch in Model.RestaurantSearch)  // Throws.
{
}

<p>@Model.somePropertyName</p> <!-- Also throws -->

WPF Control Creation Order and Events

WPF控件调用期间创建的InitializeComponent出现的视觉树的顺序。将引发NullReferenceException的早期创建控件的事件处理程序,等火initializecomponent参考后期创建的控件。

例如:

<Grid>
    <!-- Combobox declared first -->
    <ComboBox Name="comboBox1" 
              Margin="10"
              SelectedIndex="0" 
              SelectionChanged="comboBox1_SelectionChanged">
        <ComboBoxItem Content="Item 1" />
        <ComboBoxItem Content="Item 2" />
        <ComboBoxItem Content="Item 3" />
    </ComboBox>

    <!-- Label declared later -->
    <Label Name="label1" 
           Content="Label"
           Margin="10" />
</Grid>

这里combobox1是之前创建的标签。如果combobox1_selectionchanged试图参考Label1就没有了。

private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    label1.Content = comboBox1.SelectedIndex.ToString(); // NullReference here!!
}

改变在XAML的声明的顺序(即:上市前一combobox1,忽视设计理念,问题至少可以解决NullReferenceException这里。

Cast with as

var myThing = someObject as Thing;

这不抛出一个,但返回一个空时转换失败(当someobject本身是空的)。所以要意识到。

LINQ FirstOrDefault() and SingleOrDefault()

普通版本first()和single()抛出异常的时候有什么。“ordefault”版本还那么空。所以要意识到。

foreach

每一把当您尝试迭代空集合。通常由返回集合的方法的意外空结果引起。

 List<int> list = null;    
 foreach(var v in list) { } // exception

更现实的示例-从xml文档中选择节点。如果未找到节点,将抛出,但初始调试显示所有属性有效:

 foreach (var node in myData.MyXml.DocumentNode.SelectNodes("//Data"))

避免的方法

Explicitly check for null, and ignore null values.

如果期望引用有时为空,则可以在访问实例成员之前检查它为空:

void PrintName(Person p) {
    if (p != null) {
        Console.WriteLine(p.Name);
    }
}

Explicitly check for null, and provide a default value.

希望返回实例的方法调用可以返回null,例如找不到要查找的对象。当情况发生时,您可以选择返回默认值:

string GetCategory(Book b) {
    if (b == null)
        return "Unknown";
    return b.Category;
}

Explicitly check for null from method calls and throw a custom exception.

您也可以抛出自定义异常,只在调用代码中捕获异常:

string GetCategory(string bookTitle) {
    var book = library.FindBook(bookTitle);  // This may return null
    if (book == null)
        throw new BookNotFoundException(bookTitle);  // Your custom exception
    return book.Category;
}

Use Debug.Assert if a value should never be null, to catch the problem earlier than the exception occurs.

当你知道一个方法也许可以在开发过程中,但实际上不应该返回null,你可以使用调试。assert()打破尽快当它发生:

string GetTitle(int knownBookID) {
    // You know this should never return null.
    var book = library.GetBook(knownBookID);  

    // Exception will occur on the next line instead of at the end of this method.
    Debug.Assert(book != null, "Library didn't return a book for known book ID.");

    // Some other code ...

    return book.Title; // Will never throw NullReferenceException in Debug mode.
}

虽然这张支票将不会在你的发布版本,使它抛出NullReferenceException时再书= = null在发布模式下运行。

Use GetValueOrDefault() for nullable value types to provide a default value when they are null.

DateTime? appointment = null;
Console.WriteLine(appointment.GetValueOrDefault(DateTime.Now));
// Will display the default value provided (DateTime.Now), because appointment is null.

appointment = new DateTime(2022, 10, 20);
Console.WriteLine(appointment.GetValueOrDefault(DateTime.Now));
// Will display the appointment date, not the default

Use the null coalescing operator: ?? [C#] or If() [VB].

在遇到NULL时提供默认值的简写:

IService CreateService(ILogger log, Int32? frobPowerLevel)
{
    var serviceImpl = new MyService(log ?? NullLog.Instance);

    // Note that the above "GetValueOrDefault()" can also be rewritten to use
    // the coalesce operator:
    serviceImpl.FrobPowerLevel = frobPowerLevel ?? 5;
}

Use the null condition operator: ?. (available in C# 6 and VB.NET 14):

这有时也被称为安全导航或埃尔维斯(后形状)操作员。如果运算符左侧的表达式为NULL,则不会对右侧进行评估,而是返回null。这意味着这样的情况:

var title = person.Title.ToUpper();

人如果没有标题,这将抛出一个异常,因为它试图调用一个空值属性直接。

C # 5及以下,这可以保护:

var title = person.Title == null ? null : person.Title.ToUpper();

现在标题变量将是NULL,而不是抛出异常。C # 6介绍这一较短的语法:

var title = person.Title?.ToUpper();

这将导致标题变为空,并打电话给ToUpper是不是如果的人。标题为空。

当然,你还必须检查标题为空或零条件运算符一起使用null合并运算符(?提供默认值:

// regular null check
int titleLength = 0;
if (title != null)
    titleLength = title.Length; // If title is null, this would throw NullReferenceException

// combining the `?` and the `??` operator
int titleLength = title?.Length ?? 0;
answer2: 回答2:

NullReference Exception — Visual Basic

The NullReference Exception for Visual Basic is no different from the one in C#. After all, they are both reporting the same exception defined in the .NET Framework which they both use. Causes unique to Visual Basic are rare (perhaps only one).

This answer will use Visual Basic terms, syntax and context. The examples used come from a large number of past Stack Overflow questions. This is to maximize relevance by using the kinds of situations often seen in posts. A bit more explanation is also provided for those who might need it. An example similar to yours is very likely listed here.

Note:

  1. This is concept-based: there is no code for you to paste into your project. It is intended to help you understand what causes a NullReferenceException (NRE), how to find it, how to fix it, and how to avoid it. An NRE can be caused many ways so this is unlikely to be your sole encounter.
  2. The examples (from Stack Overflow posts) do not always show the best way to do something in the first place.
  3. Typically, the simplest remedy is used.

Basic Meaning

The message "Object not set to instance of Object" means you are trying to use an object which has not been initialized. This boils down to one of these:

  • Your code declared an object variable, but it did not initialize it (create an instance or 'instantiate' it)
  • Something which your code assumed would initialize an object, did not
  • Possibly, other code prematurely invalidated an object still in use

Finding The Cause

Since the problem is an object reference which is Nothing, the answer is to examine them to find out which one. Then determine why it is not initialized. Hold the mouse over the various variables and Visual Studio (VS) will show their values - the culprit will be Nothing.

You should also remove any Try/Catch blocks from the relevant code, especially ones where there is nothing in the Catch block. This will cause your code to crash when it tries to use an object which is Nothing. This is what you want, because it will identify the exact location of the problem, and allow you to identify the object causing it.

A MsgBox in the Catch which displays Error while... will be of little help. This method also leads to very bad Stack Overflow questions, because the you can't describe the actual exception, the object involved or even the line of code where it happens.

You can also use the Locals Window (Debug -> Windows -> Locals) to examine your objects.

Once you know what and where the problem is, it is usually fairly easy to fix and faster than posting a new question.

See also:

Examples and Remedies

Class Objects / Creating an Instance

Dim reg As CashRegister
...
TextBox1.Text = reg.Amount         ' NRE

The problem is that Dim does not create a CashRegister object; it only declares a variable named reg of that Type. Declaring an object variable and creating an instance are two different things.

Remedy

The New operator can often be used to create the instance when you declare it:

Dim reg As New CashRegister        ' [New] creates instance, invokes the constructor

' Longer, more explicit form:
Dim reg As CashRegister = New CashRegister

When it is only appropriate to create the instance later:

Private reg As CashRegister         ' Declare
  ...
reg = New CashRegister()            ' Create instance

Note: Do not use Dim again in a procedure, including the constructor (Sub New):

Private reg As CashRegister
'...

Public Sub New()
   '...
   Dim reg As New CashRegister
End Sub

This will create a local variable, reg, which exists only in that context (sub). The reg variable with module level Scope which you will use everywhere else remains Nothing.

Missing the New operator is the #1 cause of NullReference Exceptions seen in the Stack Overflow questions reviewed.

Visual Basic tries to make the process clear repeatedly using New: Using the New Operator creates a new object and calls Sub New -- the constructor -- where your object can perform any other initialization.

To be clear, Dim (or Private) only declares a variable and its Type. The Scope of the variable - whether it exists for the entire module/class or is local to a procedure - is determined by where it is declared. Private | Friend | Public defines the access level, not Scope.

For more information, see:


Arrays

Arrays must also be instantiated:

Private arr as String()

This array has only been declared, not created. There are several ways to initialize an array:

Private arr as String() = New String(10){}
' or
Private arr() As String = New String(10){}

' For a local array (in a procedure) and using 'Option Infer':
Dim arr = New String(10) {}

Note: Beginning with VS 2010, when initializing a local array using a literal and Option Infer, the As <Type> and New elements are optional:

Dim myDbl As Double() = {1.5, 2, 9.9, 18, 3.14}
Dim myDbl = New Double() {1.5, 2, 9.9, 18, 3.14}
Dim myDbl() = {1.5, 2, 9.9, 18, 3.14}

The data Type and array size are inferred from the data being assigned. Class/Module level declarations still require As <Type> with Option Strict:

Private myDoubles As Double() = {1.5, 2, 9.9, 18, 3.14}

Example: Array of class objects

Dim arrFoo(5) As Foo

For i As Integer = 0 To arrFoo.Count - 1
   arrFoo(i).Bar = i * 10       ' Exception
Next

The array has been created, but the Foo objects in it have not.

Remedy

For i As Integer = 0 To arrFoo.Count - 1
    arrFoo(i) = New Foo()         ' Create Foo instance
    arrFoo(i).Bar = i * 10
Next

Using a List(Of T) will make it quite difficult to have an element without a valid object:

Dim FooList As New List(Of Foo)     ' List created, but it is empty
Dim f As Foo                        ' Temporary variable for the loop

For i As Integer = 0 To 5
    f = New Foo()                    ' Foo instance created
    f.Bar =  i * 10
    FooList.Add(f)                   ' Foo object added to list
Next

For more information, see:


Lists and Collections

.NET collections (of which there are many varieties - Lists, Dictionary, etc.) must also instantiated or created.

Private myList As List(Of String)
..
myList.Add("ziggy")           ' NullReference

You get the same exception for the same reason - m

nullreference例外,Visual Basic

Visual Basic nullreference例外是从C #一没有什么不同。毕竟,它们都报告在.NET框架中定义的相同的异常,它们都使用。Visual Basic独特的原因是罕见的(也许只有一个)。

这个答案将使用Visual Basic术语,语法和上下文。使用的例子来自大量的堆栈溢出的问题 过去。这是最大化的相关性,通过使用经常出现在职位的各种情况。对于那些可能需要它的人,也提供了更多的解释。类似于你的例子很可能在这里列出。

注:

  1. This is concept-based: there is no code for you to paste into your project. It is intended to help you understand what causes a NullReferenceException (NRE), how to find it, how to fix it, and how to avoid it. An NRE can be caused many ways so this is unlikely to be your sole encounter.
  2. The examples (from Stack Overflow posts) do not always show the best way to do something in the first place.
  3. Typically, the simplest remedy is used.

Basic Meaning

“对象未设置为对象实例”的消息表示您试图使用未初始化的对象。这归结为其中之一:

  • Your code declared an object variable, but it did not initialize it (create an instance or 'instantiate' it)
  • Something which your code assumed would initialize an object, did not
  • Possibly, other code prematurely invalidated an object still in use

Finding The Cause

因为问题是一个没有引用的对象引用,答案是检查它们找出哪一个。然后确定为什么它没有初始化。按住鼠标在各种变量和Visual Studio(VS)将显示他们的价值-罪魁祸首将是什么。

您还应该删除任何从相关代码中的尝试/捕获块,特别是那些在catch块中没有任何内容的地方。这将导致您的代码崩溃时,它试图使用一个对象,这是什么。这就是你想要的,因为它会识别问题的确切位置,并允许你识别导致它的对象。

这一消息显示错误的捕捉而…会有点帮助。这种方法也会导致非常糟糕的堆栈 溢出问题,因为你不能描述实际的例外,所涉及的对象或代码行,它发生在哪里。

你也可以使用本地窗口(windows调试- >;>;当地人)来检查你的目标。

一旦你知道问题的所在和位置,通常比发布一个新问题要容易而且速度快。

参见:

实例 and Remedies

Class Objects / Creating an Instance

Dim reg As CashRegister
...
TextBox1.Text = reg.Amount         ' NRE

问题是,暗不创建一个收银机的对象;它只声明一个变量命名注册的类型。声明对象变量和创建实例是两个不同的事情。

救济

新运算符通常用于在声明时创建实例:

Dim reg As New CashRegister        ' [New] creates instance, invokes the constructor

' Longer, more explicit form:
Dim reg As CashRegister = New CashRegister

仅在稍后创建实例时合适:

Private reg As CashRegister         ' Declare
  ...
reg = New CashRegister()            ' Create instance

注: Do not use Dim again in a procedure, including the constructor (Sub New):

Private reg As CashRegister
'...

Public Sub New()
   '...
   Dim reg As New CashRegister
End Sub

这将创建一个局部变量,注册区,仅存在于该上下文(子)。与模块级别的范围,您将在其他地方使用的注册表变量仍然没有。

缺少新的算子是nullreference异常堆栈溢出的问题了 看到# 1原因。

Visual Basic试图让过程清晰的反复使用新:使用new运算符创建一个新对象和调用子新的构造函数,对象可以执行任何其他要求alization.

To be clear, Dim (or Private) only declares a variable and its Type. The Scope of the variable - whether it exists for the entire module/class or is local to a procedure - is determined by where it is declared. Private | Friend | Public defines the access level, not Scope.

For more information, see:


Arrays

Arrays must also be instantiated:

Private arr as String()

This array has only been declared, not created. There are several ways to initialize an array:

Private arr as String() = New String(10){}
' or
Private arr() As String = New String(10){}

' For a local array (in a procedure) and using 'Option Infer':
Dim arr = New String(10) {}

注: Beginning with VS 2010, when initializing a local array using a literal and Option Infer, the As <Type> and New elements are optional:

Dim myDbl As Double() = {1.5, 2, 9.9, 18, 3.14}
Dim myDbl = New Double() {1.5, 2, 9.9, 18, 3.14}
Dim myDbl() = {1.5, 2, 9.9, 18, 3.14}

The data Type and array size are inferred from the data being assigned. Class/Module level declarations still require As <Type> with Option Strict:

Private myDoubles As Double() = {1.5, 2, 9.9, 18, 3.14}

Example: Array of class objects

Dim arrFoo(5) As Foo

For i As Integer = 0 To arrFoo.Count - 1
   arrFoo(i).Bar = i * 10       ' Exception
Next

The array has been created, but the Foo objects in it have not.

救济

For i As Integer = 0 To arrFoo.Count - 1
    arrFoo(i) = New Foo()         ' Create Foo instance
    arrFoo(i).Bar = i * 10
Next

Using a List(Of T) will make it quite difficult to have an element without a valid object:

Dim FooList As New List(Of Foo)     ' List created, but it is empty
Dim f As Foo                        ' Temporary variable for the loop

For i As Integer = 0 To 5
    f = New Foo()                    ' Foo instance created
    f.Bar =  i * 10
    FooList.Add(f)                   ' Foo object added to list
Next

For more information, see:


Lists and Collections

.NET collections (of which there are many varieties - Lists, Dictionary, etc.) must also instantiated or created.

Private myList As List(Of String)
..
myList.Add("ziggy")           ' NullReference

You get the same exception for the same reason - m

c#  .net  vb.net  null  nullreferenceexception