对象引用未设置为响应时对象错误的实例

时间:2016-02-13 15:17:50

标签: c# arrays list class arraylist

我在SoapUI上遇到Object reference not set to an instance of an object.错误。我使用记录器来检查record是否包含正确的StartTimeEndTime但是由于某种原因,当我尝试添加包含{{1}的record对象时,我收到了该错误}和userId进入响应。此外,TimePeriod是具有从result图层返回的信息的变量。任何有关这方面的帮助将不胜感激。

DataAccess

以下是我的回复代码:

GetUserResponse response = new GetUserResponse();
UserRecord record = new UserRecord();
record.UserId = userId;
record.timePeriodList = new List<TimePeriod>();
for (int i = 0; i < result.Count; i += 2)
{
    TimePeriod timeData = new TimePeriod();
    timeData.StartTime = result[i].Time;
    timeData.EndTime = result[i + 1].Time;
    record.timePeriodList.Add(timeData);
}
response.UserRecordList.Add(record); // line I get that error

1 个答案:

答案 0 :(得分:2)

当您尝试插入元素时,需要声明列表UserRecordList的新实例,因为它将是null

GetUserResponse response = new GetUserResponse();
response.UserRecordList = new List<UserRecord>();

或者,您可以在类级别或构造函数中添加它。

public class GetUserResponse
{
    private List<UserRecord> userRecordList = new List<UserRecord>();

    public List<UserRecord> UserRecordList
    {
        get { return userRecordList; }
        set { userRecordList = value; }
    }
}