c# - 如何将模型的实例添加到列表中
问题描述
我正在完成一个没有数据库的 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 变量来执行此操作吗?
我需要向我的服务类添加方法吗?
任何想法将不胜感激!
提前致谢。
解决方案
您的代码存在许多问题。首先,您在 getter ( Things
) 中做的太多了。就其本质而言,属性应该是轻量级的数据访问成员。如果您需要做繁重的工作,那就是您考虑使用方法而不是属性的时候。
有了这个,你就有了一个问题:每次有人访问你的列表时,它都会被重建,因为这是你的 getter 内部的逻辑;您每次都重新实例化并构建您的列表。
第三,您需要在课堂之外提供对您财产的访问权限。当前您的Things
属性是private
,因此将其更改为public
or internal
。
这是一种简单的方法:
public List<Thing> Things { get; } = new List<Thing>();
它是一个公共属性(可在您的类之外访问),在构造类时实例化列表并提供对列表的只读访问,即不能为其分配新的列表实例。以下是如何从另一个类中使用它:
this._thingService.Things.Add(...);
推荐阅读
- python - 计算二维数组中空数组出现的次数
- html - 试图实现这种类型的滑块
- java - 将用户输入的元素的总和输出到 ArrayList Java
- google-chrome-extension - 从 chrome 扩展调用后端 API
- json - python3:json.dump(s) 的行长?
- javascript - 如何使用 javascript/jquery 将大型 html 块附加到刀片文件?
- c# - 我需要包含哪些软件包才能使用 AutomationCore?
- c# - 添加 Outlook 365 日历事件而无需多次登录 C#
- oracle - 在 oracle 11g 中将数据从临时表加载到主表
- c++ - 我的 C++ 语言中的蛮力算法问题