声明对象集合的问题

时间:2019-06-19 00:55:14

标签: c#

当我运行此代码时,当我尝试将标签添加到tagCollection时,出现Null Reference异常错误。我很确定这是我声明tagCollection的方式的问题,但是我不确定我要去哪里出错。

2个类的设置是让我在完成数据收集后将集合序列化回JSON文件。

<div class="pane">
        <button class='remove-button'>[x]</button>
        <h3>Horse</h3>
        <p>The horse is one of two extant subspecies of Equus ferus. It is an odd-toed ungulate mammal belonging to the taxonomic family Equidae. The horse has evolved over the past 45 to 55 million years from a small multi-toed creature, Eohippus, into thelarge, single-toed animal of today.</p>
      </div>

      <div class="pane">
        <button class='remove-button'>[x]</button>
        <h3>Donkey</h3>
        <p>The donkey or ass (Equus africanus asinus) is a domesticated member of the horse family, Equidae. The wild ancestor of the donkey is the African wild ass, E. africanus. The donkey has been used as a working animal for at least 5000 years.</p>
      </div>
      
      <div class="pane">
        <button class='remove-button'>[x]</button>
        <h3>Cat</h3>
        <p>The domestic cat (Latin: Felis catus) is a small, typically furry, carnivorous mammal. They are often called house cats when kept as indoor pets or simply cats when there is no need to distinguish them from other felids and felines. Cats are oftenvalued by humans for companionship and for their ability to hunt vermin.</p>
      </div>

1 个答案:

答案 0 :(得分:2)

更改此:

private TagCollection tagCollection;

为此:

private TagCollection tagCollection = new TagCollection();

您只是忘了调用集合中的新项。

更新:您还需要更改标签的声明(对用户@John的信用):

public List<Tag> Tags { get; set; } = new List<Tag>();