.net “未将对象引用设置为对象的实例”是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/779091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 12:34:02  来源:igfitidea点击:

What does "Object reference not set to an instance of an object" mean?

.netnullreferenceexception

提问by mohammad reza

I am receiving this error and I'm not sure what it means?

我收到此错误,但不确定这意味着什么?

Object reference not set to an instance of an object.

你调用的对象是空的。

回答by Iain

Variables in .NET are either reference types or value types. Value types are primitives such as integersand booleansor structures (and can be identified because they inherit from System.ValueType). Boolean variables, when declared, have a default value:

.NET 中的变量是引用类型或值类型。值类型是基元,例如整数布尔值或结构(并且可以识别,因为它们继承自System.ValueType)。布尔变量在声明时具有默认值:

bool mybool;
//mybool == false

Reference types, when declared, do not have a default value:

引用类型在声明时没有默认值:

class ExampleClass
{
}

ExampleClass exampleClass; //== null

If you try to access a member of a class instance using a null reference then you get a System.NullReferenceException. Which is the same as Object reference not set to an instance of an object.

如果您尝试使用空引用访问类实例的成员,则会得到System.NullReferenceException。这与Object reference not set to an instance of an object 相同

The following code is a simple way of reproducing this:

以下代码是重现此内容的简单方法:

static void Main(string[] args)
{
    var exampleClass = new ExampleClass();
    var returnedClass = exampleClass.ExampleMethod();
    returnedClass.AnotherExampleMethod(); //NullReferenceException here.
}

class ExampleClass
{
    public ReturnedClass ExampleMethod()
    {
        return null;
    }
}

class ReturnedClass
{
    public void AnotherExampleMethod()
    {
    }
}

This is a very common error and can occur because of all kinds of reasons. The root cause really depends on the specific scenario that you've encountered.

这是一个非常常见的错误,可能由于各种原因而发生。根本原因实际上取决于您遇到的特定情况。

If you are using an API or invoking methods that may return null then it's important to handle this gracefully. The main method above can be modified in such a way that the NullReferenceException should never be seen by a user:

如果您正在使用 API 或调用可能返回 null 的方法,那么优雅地处理它很重要。上面的主要方法可以修改为用户永远不会看到 NullReferenceException:

static void Main(string[] args)
{
    var exampleClass = new ExampleClass();
    var returnedClass = exampleClass.ExampleMethod();

    if (returnedClass == null)
    {
        //throw a meaningful exception or give some useful feedback to the user!
        return;
    }

    returnedClass.AnotherExampleMethod();
}

All of the above really just hints of .NET Type Fundamentals, for further information I'd recommend either picking up CLR via C#or reading this MSDN articleby the same author - Jeffrey Richter. Also check out, much more complex, exampleof when you can encounter a NullReferenceException.

以上所有内容实际上只是对 .NET 类型基础知识的提示,有关更多信息,我建议您通过 C#获取CLR或阅读同一作者 - Jeffrey Richter 撰写的这篇MSDN 文章。另请查看更复杂的示例,了解何时会遇到 NullReferenceException。

Some teams using Resharper make use of JetBrains attributesto annotate code to highlight where nulls are (not) expected.

一些使用 Resharper 的团队利用JetBrains 属性来注释代码,以突出显示(不)期望空值的位置。

回答by Jay

Another easy way to get this:

另一种简单的方法来获得这个:

 Person myPet = GetPersonFromDatabase();
 // check for myPet == null... AND for myPet.PetType == null
 if ( myPet.PetType == "cat" ) <--- fall down go boom!

回答by Adithya Kumaranchath

In a nutshell it means.. You are trying to access an object without instantiating it.. You might need to use the "new" keyword to instantiate it first i.e create an instance of it.

简而言之,这意味着.. 您试图访问一个对象而不实例化它.. 您可能需要先使用“new”关键字来实例化它,即创建它的一个实例。

For eg:

例如:

public class MyClass
{
   public int Id {get; set;}
}

MyClass myClass;

myClass.Id = 0; <----------- An error will be thrown here.. because myClass is null here...

You will have to use:

你将不得不使用:

myClass = new MyClass();
myClass.Id = 0;

Hope I made it clear..

希望我说清楚了..

回答by dkpatt

Not to be blunt but it means exactly what it says. One of your object references is NULL. You'll see this when you try and access the property or method of a NULL'd object.

不要直言不讳,但这正是它所说的意思。您的对象引用之一是 NULL。当您尝试访问 NULL 对象的属性或方法时,您会看到这一点。

回答by J.W.

It means you did something like this.

这意味着你做了这样的事情。

Class myObject = GetObjectFromFunction();

And withoutdoing

没有

if(myObject!=null), you go ahead do myObject.Method();

if(myObject!=null),你继续做 myObject.Method();

回答by TStamper

what does this error mean? Object reference not set to an instance of an object.

这个错误是什么意思?你调用的对象是空的。

exactly what it says, you are trying to use a null object as if it was a properly referenced object.

正是它所说的,您正在尝试使用一个空对象,就好像它是一个正确引用的对象一样。

回答by Syed Tayyab Ali

Most of the time, when you try to assing value into object, and if the value is null, then this kind of exception occur. Please check this link.

大多数情况下,当您尝试将值赋值给对象时,如果值为空,则会发生这种异常。请检查此链接

for the sake of self learning, you can put some check condition. like

为了自学,你可以放一些检查条件。喜欢

if (myObj== null)
Console.Write("myObj is NULL");

回答by Liam

If I have the class:

如果我有课:

public class MyClass
{
   public void MyMethod()
   {

   }
}

and I then do:

然后我做:

MyClass myClass = null;
myClass.MyMethod();

The second line throws this exception becuase I'm calling a method on a reference typeobject that is null(I.e. has not been instantiatedby calling myClass = new MyClass())

第二行抛出此异常,因为我正在调用一个引用类型对象上的方法null(即尚未 通过调用实例化myClass = new MyClass()