首页 > 解决方案 > 如何将模型的实例添加到列表中

问题描述

我正在完成一个没有数据库的 MVC 教程。

服务等级

namespace Domain.Services
{
    public class ThingService
    {
        private List<Thing> _things;
        private List<Thing> Things
        {
            get
            {
                 if (this._things == null)
                 {
                     this._things = new List<Thing>();
                     this._things.Add(new Thing()
                     {
                         ID = 1,
                         Name = "The red thing",
                         Color = "Red",
                         Size = "Small",
                         Length = 55,
                         DateAvailable = DateTime.Parse("1/1/2018"),
                         IsActive = true
                     });

                     // Add more things

               }

               return this._things;
            }
        }

控制器

namespace WWW.Controllers
{
    public class HomeController : Controller
    {
        private readonly ThingService _thingService;

        public HomeController()
        {
            this._thingService = new ThingService();
        }

        public ActionResult AddThing()
        {
            //add code for a new thing

            return View();
        }
    }
}

我需要帮助将我的模型的新实例添加到列表中(_things?Things?)。我已经尝试过服务类的方式并得到范围解析错误。

我可以通过控制器中可用的 _thingService 变量来执行此操作吗?

我需要向我的服务类添加方法吗?

任何想法将不胜感激!

提前致谢。

标签: c#oopmodel-view-controller

解决方案


您的代码存在许多问题。首先,您在 getter ( Things) 中做的太多了。就其本质而言,属性应该是轻量级的数据访问成员。如果您需要做繁重的工作,那就是您考虑使用方法而不是属性的时候。

有了这个,你就有了一个问题:每次有人访问你的列表时,它都会被重建,因为这是你的 getter 内部的逻辑;您每次都重新实例化并构建您的列表。

第三,您需要在课堂之外提供对您财产的访问权限。当前您的Things属性是private,因此将其更改为publicor internal

这是一种简单的方法:

public List<Thing> Things { get; } = new List<Thing>();

它是一个公共属性(可在您的类之外访问),在构造类时实例化列表并提供对列表的只读访问,即不能为其分配新的列表实例。以下是如何从另一个类中使用它:

this._thingService.Things.Add(...);

推荐阅读