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

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

这意味着什么,我可以做什么来修复这个错误?


当前回答

请注意,无论情况如何,.NET中的原因总是相同的:

您正在尝试使用值为Nothing/null的引用变量。当引用变量的值为Nothing/null时,这意味着它实际上没有保存对堆上存在的任何对象实例的引用。您要么从未向变量赋值,要么从未创建分配给变量的值的实例,要么手动将变量设置为Nothing/null,要么为您调用了将变量设置成Nothing/nnull的函数。

其他回答

抛出此异常的一个示例是:当您试图检查某个对象时,该对象为空。

例如:

string testString = null; //Because it doesn't have a value (i.e. it's null; "Length" cannot do what it needs to do)

if (testString.Length == 0) // Throws a nullreferenceexception
{
    //Do something
} 

当您尝试对尚未实例化的对象(即上面的代码)执行操作时,.NET运行时将抛出NullReferenceException。

与ArgumentNullException相比,ArgumentNullException通常在方法期望传递给它的内容不为null时作为防御措施抛出。

更多信息请参见C#NullReferenceException和Null参数。

您正在使用包含空值引用的对象。所以它给出了一个空异常。在本例中,字符串值为空,在检查其长度时发生异常。

例子:

string value = null;
if (value.Length == 0) // <-- Causes exception
{
    Console.WriteLine(value); // <-- Never reached
}

异常错误为:

未处理的异常:System.NullReferenceException:对象引用未设置为实例对象的。位于Program.Main()

如果在保存或编译构建过程中收到此消息,只需关闭所有文件,然后打开任何文件进行编译和保存即可。

对我来说,原因是我重命名了文件,而旧文件仍然打开。

当您尝试使用的类的对象未实例化时,会发生NullReferenceException或未设置对象实例的Object引用。例如:

假设您有一个名为Student的班级。

public class Student
{
    private string FirstName;
    private string LastName;
    public string GetFullName()
    {
        return FirstName + LastName;
    }
}

现在,考虑另一个你试图检索学生全名的班级。

public class StudentInfo
{      
    public string GetStudentName()
    {
        Student s;
        string fullname = s.GetFullName();
        return fullname;
    }        
}

如以上代码所示Student s-只声明Student类型的变量,注意Student类此时未实例化。因此,当执行s.GetFullName()语句时,它将抛出NullReferenceException。

TL;DR:尝试使用Html.Parate而不是Renderpage


当我试图通过发送模型在视图中呈现视图时,我得到的对象引用未设置为对象的实例,如下所示:

@{
    MyEntity M = new MyEntity();
}
@RenderPage("_MyOtherView.cshtml", M); // error in _MyOtherView, the Model was Null

调试显示模型在MyOtherView中为Null。直到我将其更改为:

@{
    MyEntity M = new MyEntity();
}
@Html.Partial("_MyOtherView.cshtml", M);

它奏效了。

此外,我没有Html.Paraal的原因是,Visual Studio有时会在Html.Partial下抛出看起来像错误的曲线,如果它位于不同构造的foreach循环中,即使它不是真正的错误:

@inherits System.Web.Mvc.WebViewPage
@{
    ViewBag.Title = "Entity Index";
    List<MyEntity> MyEntities = new List<MyEntity>();
    MyEntities.Add(new MyEntity());
    MyEntities.Add(new MyEntity());
    MyEntities.Add(new MyEntity());
}
<div>
    @{
        foreach(var M in MyEntities)
        {
            // Squiggly lines below. Hovering says: cannot convert method group 'partial' to non-delegate type Object, did you intend to envoke the Method?
            @Html.Partial("MyOtherView.cshtml");
        }
    }
</div>

但我能够运行应用程序,没有出现任何问题。通过将foreach循环的结构更改为如下所示,我能够消除该错误:

@foreach(var M in MyEntities){
    ...
}

虽然我觉得这是因为Visual Studio误读了符号和括号。