C# 使用构造函数初始化MVC模型属性
我有一个MVC模型C# 使用构造函数初始化MVC模型属性,c#,asp.net-mvc,C#,Asp.net Mvc,我有一个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 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; }
}
公共类协议摘要
{
公共字符串MasteredTask{get;set;}
公共字符串NewTask{get;set;}
公共列表列表{get;set;}
}
公共课助理技术
{
公共字符串类型{get;set;}
公共字符串ScheduleForUse{get;set;}
公共字符串存储位置{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"
};
这就是你想要的吗?我会尽量让瓦林德·辛格的答案更加完整:
// 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" }
}
};
//假设您需要ProtocolSummary的实例
var protocolSummary=新的protocolSummary()
{
MasteredTask=“某些主任务名称”,
NewTask=“新任务开始了”,
ATList=新列表()
{
new AssistTech(){Type=“Some text”,ScheduleForUse=“Some other text”,StorageLocation=“Some other text”},
new AssistTech(){Type=“Some text”,ScheduleForUse=“Some other text”,StorageLocation=“Some other text”}
}
};
那么您想要构造哪个类?为什么你不能写一个构造函数呢?你能把调用代码显示在你想构建它们的地方吗?