首页 > 解决方案 > 在对象中查找属性,然后将项目添加到它的列表属性中

问题描述

我太愚蠢了,我正在寻找向已经存在的属性添加一个新项目。

这是对我正在做的事情的一个非常简单的看法。它导致找不到对象引用。我究竟做错了什么?

using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var ids = new [] { 1, 2, 3 };

            var libraries = ids.Select(id => new Library {Id = id}).ToList();

            //find the property 
            var library = libraries.FirstOrDefault(x => x.Id == 2);

            //add a title to that property
            var title = "Harry Potter";
            library.Titles.Add(title); //error here
        }
    }

    public class Library
    {
        public int Id { get; set; }
        public List<string> Titles { get; set; }
    }
}

标签: c#listobject

解决方案


您从未使用列表初始化Titles属性,因此您无法向null. 您当前正在做的事情相当于:

List<string> myList = null;
myList.Add("foo");

您使用的是类属性而不是变量,但问题是一样的。您需要先实例化列表,然后才能访问它并向其中添加项目,这可以通过以下三种方式之一完成:

 Select(id => new Library {Id = id, Titles = new List<string>()})

或通过构造函数:

public class Library
{
    public int Id { get; set; }
    public List<string> Titles { get; set; }

    public Library()
    {
        this.Titles = new List<string>();
    }
}

或通过物业本身:

public class Library
{
    public int Id { get; set; }
    public List<string> Titles { get; set; } = new List<string>();
}

我个人更喜欢第三种选择,但其中任何一种都可以。


推荐阅读