通常这意味着在应用程序中引用了一个空对象。为了解决这个问题,您可以使用以下步骤:
以下是一个示例,它创建了一个名为“person”的Person类,并在另一个类中引用它。如果在引用“person”之前未对其进行实例化,则会引发Object reference not set error。
public class Person
{
public string Name { get; set; }
}
public class MainClass
{
public void SomeMethod()
{
Person person;
// If person is not initialized, the following line will cause an Object reference not set error.
string name = person.Name;
}
}
要修复此错误,请确保在使用“person”之前将其实例化。
public class MainClass
{
public void SomeMethod()
{
Person person = new Person();
// Now person is initialized and the following line won't cause an Object reference not set error.
string name = person.Name;
}
}