首页 > 解决方案 > 元素未添加到列表 .NET Core

问题描述

我有一个压力很大的问题,我无法将元素添加到列表中,该操作不会引发任何异常或任何东西,只是没有添加元素。

结构如下。

我有一个班级,我将其用作内存数据库。在该类中,我有一个具有一些默认值的对象列表。

对象类型是 Author 具有以下结构

public class Author 
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}

列表结构是这样的

public class InMemoryStore
{
     public List<Author> Authors => new List<Author>
     {
            new Author(new Guid("5784f8b7-31b5-4886-8874-aff5241164a8"), "test"),
     } 
}

我正在将该类注册为 Scoped 服务并将其注入我的测试控制器中,只需执行添加,它不会产生任何结果。它不会添加它不会引发任何异常的项目。我很困惑。

    private readonly InMemoryStore _inMemoryStore;
    public AuthorsController(InMemoryStore inMemoryStore)
    {
        _inMemoryStore = inMemoryStore;
    }

在行动

   _inMemoryStore.Authors.Add(author);

在动作中创建相同的列表,有效

标签: c#generics.net-core

解决方案


我想你的意思是:

public List<Author> Authors { get; } = new List<Author>
{
    new Author(new Guid("5784f8b7-31b5-4886-8874-aff5241164a8"), "test"),
} 

推荐阅读