我有以下代码:
try
{
var result =
from entry in feed.Descendants(a + "entry")
let content = entry.Element(a + "content")
let properties = content.Element(m + "properties")
let notes = properties.Element(d + "DetailsJSON")
let questionMessage = properties.Element(d + "QuestionText")
let title = properties.Element(d + "Title")
let partitionKey = properties.Element(d + "PartitionKey")
where partitionKey.Value == "0001I" && title != null
select new Question
{
Notes = notes.Value ?? "n/a",
Title = title.Value,
QuestionMessage = questionMessage.Value
};
// xx
IList<Question> resultx = null;
foreach (var question in result)
{
resultx.Add(question);
}
// yy
return result;
}
catch (Exception ex)
{
throw new InvalidOperationException("GetQuestions.Get problem", ex);
};
如果我在xx和yy之间注释掉部分代码,那么它就可以了。否则我得到一个例外说:
ex {"Object reference not set to an instance of an object."} System.Exception {System.NullReferenceException}
有人可以就我可能做错的事情给我一些想法吗?
答案 0 :(得分:3)
您的列表为null
,因此NullReferenceException
:
IList<Question> resultx = null;
foreach (var question in result)
{
resultx.Add(question); // Ouch. resultx is set to null above here
}
您需要将列表初始化为List<Question>
,而不是null
:
IList<Question resultx = new List<Question>();
// .. the rest of the code
答案 1 :(得分:1)
您的resultx
已明确设置为null,因此在resultx.Add()
后,您会获得NullReferenceException
。您需要先初始化列表。