System.NullReferenceException:将项目添加到列表时

尝试将项目添加到列表时遇到问题。我看到很多问题,但在我的情况下我仍然不明白。这是我的定义:


public class DBStatus

    {

        [DataMember]

        public DBOperation Type { get; set; }

        [DataMember]

        public List<DBMessageType> Message { get; set; }

        [DataMember]

        public List<string> InnerException { get; set; }

    }

我声明了这个类并尝试添加一个项目。


private void button19_Click_1(object sender, EventArgs e)

    {

        DBStatus dbstst = new DBStatus();

        dbstst.Message.Add(DBMessageType.INVALID_OR_EXPIRED_FUNCTION_REQUEST);

        dbstst.InnerException.Add("testing code");


        int k = 0;

    }

添加项目时出现 System.NullReferenceException。


错误消息:“System.NullReferenceException:'未将对象引用设置为对象的实例。'”


我知道我的最后两个列表项是空的 post 声明,为什么我不能添加?


弑天下
浏览 196回答 1
1回答

繁星淼淼

默认情况下,列表为空,您需要在向列表中添加元素之前初始化列表选项1 :private void button19_Click_1(object sender, EventArgs e)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; DBStatus dbstst = new DBStatus();&nbsp; &nbsp; &nbsp; &nbsp; dbstst.Message = new List<DBMessageType>();&nbsp; &nbsp; &nbsp; &nbsp; dbstst.Message.Add(DBMessageType.INVALID_OR_EXPIRED_FUNCTION_REQUEST);&nbsp; &nbsp; &nbsp; &nbsp; dbstst.InnerException = new List<string>();&nbsp; &nbsp; &nbsp; &nbsp; dbstst.InnerException.Add("testing code");&nbsp; &nbsp; &nbsp; &nbsp; int k = 0;&nbsp; &nbsp; }选项 2: 您也可以通过类构造函数执行此操作:public class DBStatus&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; [DataMember]&nbsp; &nbsp; &nbsp; &nbsp; public DBOperation Type { get; set; }&nbsp; &nbsp; &nbsp; &nbsp; [DataMember]&nbsp; &nbsp; &nbsp; &nbsp; public List<DBMessageType> Message { get; set; }&nbsp; &nbsp; &nbsp; &nbsp; [DataMember]&nbsp; &nbsp; &nbsp; &nbsp; public List<string> InnerException { get; set; }&nbsp; &nbsp; &nbsp; &nbsp; public DBStatus(){ //initialize here&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Message = new List<DBMessageType>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; InnerException = new List<string>();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP