使用构造函数初始化MVC模型属性
本文关键字:模型 属性 MVC 初始化 构造函数 | 更新日期: 2023-09-27 17:50:21
我有一个MVC模型。
public class ProtocolSummary
{
public string MasteredTask { get; set; }
public string NewTask { get; set; }
public List<AssistTech> ATList { get; set; }
}
public class AssistTech
{
public string Type { get; set; }
public string ScheduleForUse { get; set; }
public string StorageLocation { get; set; }
}
如何使用构造函数初始化它?
MVC模型只是一个POCO。您可以使用默认构造函数初始化它并设置属性。或者最好使用对象初始化器
// Assuming you want an instance of ProtocolSummary
var protocolSummary = new ProtocolSummary()
{
MasteredTask = "Some Mastered task name",
NewTask = "Here goes new task"
};
这是你想要的吗?
我会尽量让Varinder Singh的回答更完整:
// Assuming you want an instance of ProtocolSummary
var protocolSummary = new ProtocolSummary()
{
MasteredTask = "Some Mastered task name",
NewTask = "Here goes new task",
ATList = new List<AssistTech>()
{
new AssistTech() { Type = "Some text", ScheduleForUse = "Some other text", StorageLocation = "Some other other text" },
new AssistTech() { Type = "Some text", ScheduleForUse = "Some other text", StorageLocation = "Some other other text" }
}
};