如何解决未将对象引用设置为对象的实例。 [重复]

时间:2021-10-13 16:54:22

This question already has an answer here:

这个问题在这里已有答案:

In my asp.net program.I set one protected list.And i add a value in list.But it shows Object reference not set to an instance of an object error

在我的asp.net程序中。我设置了一个受保护的列表。我在list中添加了一个值。但它显示对象引用未设置为对象错误的实例

protected List<string> list;
protected void Page_Load(object sender, EventArgs e)
{
     list.Add("hai");
}

How to solve this error?

如何解决这个错误?

2 个解决方案

#1


53  

You need to initialize the list first:

您需要首先初始化列表:

protected List<string> list = new List<string>();

#2


16  

I think you just need;

我想你只需要;

List<string> list = new List<string>();
list.Add("hai");

There is a difference between

两者之间有区别

List<string> list; 

and

List<string> list = new List<string>();

When you didn't use new keyword in this case, your list didn't initialized. And when you try to add it hai, obviously you get an error.

如果在这种情况下未使用new关键字,则表示您的列表未初始化。当你试图添加它时,显然你会收到错误。

#1


53  

You need to initialize the list first:

您需要首先初始化列表:

protected List<string> list = new List<string>();

#2


16  

I think you just need;

我想你只需要;

List<string> list = new List<string>();
list.Add("hai");

There is a difference between

两者之间有区别

List<string> list; 

and

List<string> list = new List<string>();

When you didn't use new keyword in this case, your list didn't initialized. And when you try to add it hai, obviously you get an error.

如果在这种情况下未使用new关键字,则表示您的列表未初始化。当你试图添加它时,显然你会收到错误。