【问题标题】:foreach in class causes error "object reference not set to an instance of an object"类中的 foreach 导致错误“对象引用未设置为对象的实例”
【发布时间】:2016-06-10 03:08:58
【问题描述】:

运行此代码时出现错误 “你调用的对象是空的” 抛出,我不知道为什么。

我已经使用调试在某些点上破坏了代码,我注意到它在传递给子注释的 foreach 后会导致错误。

如果有人能解决这个问题,我很高兴

我的 XML:

<?xml version=\"1.0\" encoding=\"utf - 8\"?>
<data type=\"array\" success=\"1\" status=\"200\">
<item>
    <id>1</id>
    <comment>aaa</comment>
    <author>john</author>
    <children/>
</item>
<item>
    <id>2</id>
    <comment>bbb</comment>
    <author>paul</author>
    <children>
        <item>
            <id>3</id>
            <comment>ccc</comment>
            <author>lisa</author>
            <children/>
        </item>
    </children>
</item>

我的代码:

 XDocument document = XDocument.Parse(xml);
 foreach (XElement item in document.Root.Elements("item"))
      {
           post.comments.Add(new Comment(item));
      }

我的班级:

 public class Comment
{
    public string id { get; set; }
    public string comment { get; set; }
    public string author { get; set; }
    public IList<Comment> children { get; set; }

    public Comment(XElement elem)
    {
        id = elem.Element("id").Value.ToString();
        comment = elem.Element("comment").Value.ToString();
        author = elem.Element("author").Value.ToString();

        foreach (XElement childComment in elem.Element("children").Elements())
        {
            children.Add(new Comment(childComment));
        }

    }
}

【问题讨论】:

标签: c# xml class xaml foreach


【解决方案1】:

Comment 的构造函数假定 public IList&lt;Comment&gt; children 已初始化,但实际上并没有创建列表的代码。

如果您可以访问System.Linq,这是最简单的:

children = elem.Element("children").Elements().Select(el => new Comment(el)).ToList();

如果您不能包含using System.Linq,您可以在循环之前简单地初始化children 成员:

children = new List<Comment>();
foreach (XElement childComment in elem.Element("children").Elements())
{
    children.Add(new Comment(childComment));
}

【讨论】:

    猜你喜欢
    • 2012-07-06
    • 1970-01-01
    • 2013-12-07
    • 2015-09-09
    • 1970-01-01
    • 2011-07-09
    • 2012-08-31
    • 2011-11-21
    • 2012-10-01
    相关资源
    最近更新 更多