0

我有以下代码:

        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}

有人可以给我一些关于我可能做错了什么的想法吗?

4

2 回答 2

3

您的清单是null,因此NullReferenceException

IList<Question> resultx = null;
foreach (var question in result)
{
    resultx.Add(question); // Ouch. resultx is set to null above here
}

您需要将列表初始化为实际上是 a List<Question>,而不是null

IList<Question resultx = new List<Question>();
// .. the rest of the code
于 2013-06-24T03:54:41.787 回答
1

resultx被明确设置为空,所以当resultx.Add()你得到一个NullReferenceException. 您需要先初始化列表。

于 2013-06-24T03:55:03.087 回答