2016-02-13 39 views
0

我在SoapUI上遇到Object reference not set to an instance of an object.錯誤。我使用記錄器來檢查record是否保留正確的StartTimeEndTime,但由於某種原因,當我嘗試將record對象(其中包含userIdTimePeriod)添加到響應中時,出現此錯誤。此外,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 

下面是代碼到我的反應:

public class GetUserResponse 
{ 
    private List<UserRecord> userRecordList; 

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

public class UserRecord 
{ 
    private string userId; 
    private List<TimePeriod> timePeriodList; 

    public string UserId 
    { 
     get { return userId; } 
     set { userId = value; } 
    } 

    public List<RbeActivationPeriod> TimePeriodList 
    { 
     get { return timePeriodList; } 
     set { timePeriodList = value; } 
    } 
} 

public class TimePeriod 
{ 
    private DateTime startTime; 
    private DateTime endTime; 

    public DateTime StartTime 
    { 
     get { return startTime; } 
     set { startTime = value; } 
    } 

    public DateTime EndTime 
    { 
     get { return endTime; } 
     set { endTime = value; } 
    } 
} 
+0

「響應」聲明在哪裏? 'userRecordList'是否被實例化? –

+0

我在你的代碼中看不到它,但我假設你已經實例化了你的變量響應? – erik

+0

@erik我爲你編輯了這篇文章。抱歉,忘了帖子上的聲明。 – user4756836

回答

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; } 
    } 
} 
+0

它說'索引超出範圍。必須是非負的,並且小於集合的大小.' on the response.add line now – user4756836

+0

@ user4756836 - most the this line'timeData.EndTime = result [i + 1] .Time;'然而這是不同的問題,所以你應該接受這個答案(它似乎已經解決了你的問題),並用索引超出範圍的異常重新發佈一個新問題。 –

相關問題