What is a NullReferenceException, and how do I fix

2020-01-22 07:10发布

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 to fix this error?

28条回答
Summer. ? 凉城
2楼-- · 2020-01-22 07:57

On the matter of "what should I do about it", there can be many answers.

A more "formal" way of preventing such error conditions while developing is applying design by contract in your code. This means you need to set class invariants, and/or even function/method preconditions and postconditions on your system, while developing.

In short, class invariants ensure that there will be some constraints in your class that will not get violated in normal use (and therefore, the class will not get in an inconsistent state). Preconditions mean that data given as input to a function/method must follow some constraints set and never violate them, and postconditions mean that a function/method output must follow the set constraints again without ever violating them. Contract conditions should never be violated during execution of a bug-free program, therefore design by contract is checked in practice in debug mode, while being disabled in releases, to maximize the developed system performance.

This way, you can avoid NullReferenceException cases that are results of violation of the constraints set. For example, if you use an object property X in a class and later try to invoke one of its methods and X has a null value, then this will lead to NullReferenceException:

public X { get; set; }

public void InvokeX()
{
    X.DoSomething(); // if X value is null, you will get a NullReferenceException
}

But if you set "property X must never have a null value" as method precondition, then you can prevent the scenario described before:

//Using code contracts:
[ContractInvariantMethod]
protected void ObjectInvariant () 
{
    Contract.Invariant ( X != null );
    //...
}

For this cause, Code Contracts project exists for .NET applications.

Alternatively, design by contract can be applied using assertions.

UPDATE: It is worth mentioning that the term was coined by Bertrand Meyer in connection with his design of the Eiffel programming language.

查看更多
ら.Afraid
3楼-- · 2020-01-22 07:57

Literally the easiest way to fix a NullReferenceExeption has two ways. If you have a GameObject for example with a script attached and a variable named rb (rigidbody) this variable will start null when you start your game.
This is why you get a NullReferenceExeption because the computer does not have data stored in that variable.

I'll be using a RigidBody variable as an example.
We can add data really easily actually in a few ways:

  1. Add a RigidBody to your object with AddComponent > Physics > Rigidbody
    Then go into your script and type rb = GetComponent<Rigidbody>();
    This line of code works best under your Start() or Awake() functions.
  2. You can add a component programmatically and assign the variable at the same time with one line of code: rb = AddComponent<RigidBody>();

Further Notes: If you want unity to add a component to your object and you might have forgotten to add one, you can type [RequireComponent(typeof(RigidBody))] above your class declaration (the space below all of your usings).
Enjoy and have fun making games!

查看更多
Viruses.
4楼-- · 2020-01-22 07:58

If one is getting this message during saving or compiling the build, just close all the files and then open any file to compile and save.

For me the reason was that I had rename the file and old file was still open.

查看更多
淡お忘
5楼-- · 2020-01-22 07:59

It means that the variable in question is pointed at nothing. I could generate this like so:

SqlConnection connection = null;
connection.Open();

That will throw the error because while I've declared the variable "connection", it's not pointed to anything. When I try to call the member "Open", there's no reference for it to resolve, and it will throw the error.

To avoid this error:

  1. Always initialize your objects before you try to do anything with them.
  2. If you're not sure whether the object is null, check it with object == null.

JetBrains' Resharper tool will identify every place in your code that has the possibility of a null reference error, allowing you to put in a null check. This error is the number one source of bugs, IMHO.

查看更多
The star\"
6楼-- · 2020-01-22 07:59

Be aware that regardless of the scenario, the cause is always the same in .NET:

You are trying to use a reference variable whose value is Nothing/null. When the value is Nothing/null for the reference variable, that means it is not actually holding a reference to an instance of any object that exists on the heap.

You either never assigned something to the variable, never created an instance of the value assigned to the variable, or you set the variable equal to Nothing/null manually, or you called a function that set the variable to Nothing/null for you.

查看更多
啃猪蹄的小仙女
7楼-- · 2020-01-22 07:59

Another case where NullReferenceExceptions can happen is the (incorrect) use of the as operator:

class Book {
    public string Name { get; set; }
}
class Car { }

Car mycar = new Car();
Book mybook = mycar as Book;   // Incompatible conversion --> mybook = null

Console.WriteLine(mybook.Name);   // NullReferenceException

Here, Book and Car are incompatible types; a Car cannot be converted/cast to a Book. When this cast fails, as returns null. Using mybook after this causes a NullReferenceException.

In general, you should use a cast or as, as follows:

If you are expecting the type conversion to always succeed (ie. you know what the object should be ahead of time), then you should use a cast:

ComicBook cb = (ComicBook)specificBook;

If you are unsure of the type, but you want to try to use it as a specific type, then use as:

ComicBook cb = specificBook as ComicBook;
if (cb != null) {
   // ...
}
查看更多
登录 后发表回答