【发布时间】:2010-10-21 05:09:32
【问题描述】:
我收到此错误,但我不确定这意味着什么?
对象引用未设置为对象的实例。
【问题讨论】:
-
NullReferenceException的几乎所有情况都是相同的。请参阅“What is a NullReferenceException in .NET?”获取一些提示。
标签: .net nullreferenceexception
我收到此错误,但我不确定这意味着什么?
对象引用未设置为对象的实例。
【问题讨论】:
NullReferenceException 的几乎所有情况都是相同的。请参阅“What is a NullReferenceException in .NET?”获取一些提示。
标签: .net nullreferenceexception
.NET 中的变量要么是引用类型,要么是值类型。值类型是诸如integers 和booleans 之类的原语或结构(并且可以识别,因为它们继承自System.ValueType)。布尔变量在声明时具有默认值:
bool mybool;
//mybool == false
引用类型在声明时没有默认值:
class ExampleClass
{
}
ExampleClass exampleClass; //== null
如果您尝试使用空引用访问类实例的成员,则会得到System.NullReferenceException。这与对象引用未设置为对象的实例相同。
以下代码是重现此内容的简单方法:
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()
{
}
}
这是一个非常常见的错误,可能由于各种原因而发生。根本原因实际上取决于您遇到的具体情况。
如果您正在使用 API 或调用可能返回 null 的方法,那么请务必优雅地处理。可以修改上面的 main 方法,使用户永远不会看到 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();
}
以上所有内容实际上只是 .NET 类型基础知识的提示,有关更多信息,我建议您选择 CLR via C# 或阅读同一作者 - Jeffrey Richter 的这篇 MSDN article。另请查看更复杂的example 何时会遇到 NullReferenceException。
一些使用 Resharper 的团队利用 JetBrains attributes 对代码进行注释,以突出显示(不)预期为空的位置。
【讨论】:
Run-time exception (line 9): Object reference not set to an instance of an object. 错误
Dim exampleClass As exampleClass而不是Dim exampleClass As New exampleClass。
简而言之,这意味着..您正在尝试访问一个对象而不实例化它..您可能需要先使用“new”关键字来实例化它,即创建它的一个实例。
例如:
public class MyClass
{
public int Id {get; set;}
}
MyClass myClass;
myClass.Id = 0; <----------- An error will be thrown here.. because myClass is null here...
你必须使用:
myClass = new MyClass();
myClass.Id = 0;
希望我说清楚..
【讨论】:
另一种简单的方法:
Person myPet = GetPersonFromDatabase();
// check for myPet == null... AND for myPet.PetType == null
if ( myPet.PetType == "cat" ) <--- fall down go boom!
【讨论】:
如果我有课:
public class MyClass
{
public void MyMethod()
{
}
}
然后我会这样做:
MyClass myClass = null;
myClass.MyMethod();
第二行引发此异常,因为我正在调用 null 的 reference type 对象上的方法(即通过调用 myClass = new MyClass() 不是 instantiated)
【讨论】:
这意味着你做了这样的事情。
Class myObject = GetObjectFromFunction();
而没有做
if(myObject!=null),你继续做myObject.Method();
【讨论】:
这个错误是什么意思?对象引用未设置为对象的实例。
正如它所说的,你正在尝试使用一个空对象,就好像它是一个正确的 引用的对象。
【讨论】:
大多数时候,当您尝试将值赋值给对象时,如果该值为 null,则会发生这种异常。 请查看this link。
为了自学,可以放一些检查条件。喜欢
if (myObj== null)
Console.Write("myObj is NULL");
【讨论】:
不要直截了当,但它的意思正是它所说的。您的对象引用之一是 NULL。当您尝试访问 NULL 对象的属性或方法时,您会看到这一点。
【讨论】: