c# - 在对象中查找属性,然后将项目添加到它的列表属性中
问题描述
我太愚蠢了,我正在寻找向已经存在的属性添加一个新项目。
这是对我正在做的事情的一个非常简单的看法。它导致找不到对象引用。我究竟做错了什么?
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; }
}
}
解决方案
您从未使用列表初始化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>();
}
我个人更喜欢第三种选择,但其中任何一种都可以。
推荐阅读
- css - 属性选择器的 Sass @each 循环
- android - CircleCI 中的单元测试因 org.gradle.internal.exceptions.LocationAwareException 而失败
- dart - 在 TextInputType 更改后控制器重置的 Flutter TextField
- python - 如何在python中沿曲线注释文本并旋转线条?
- kentico - Kentico - 网络分析仪表板不断刷新
- rabbitmq - RabbitMQ 服务器正在下降
- c# - WIMMountImageHandle 导致 ERROR_INVALID_HANDLE
- rxjs - 使用 angular5/rxjs 刷新下拉内容
- python - python3中很奇怪的事情
- matlab - 4 种不同的 Matlab 函数来估计数据的 PDF 给出 4 种不同的结果