我有一个类,想要在构造中添加一些数据,所以我可以在不使用数据库的情况下使用它:
public partial class ActionTypeList
{
public ActionTypeList()
{
new ActionTypeList { Id= "2", FName= "hanumanji" };
new ActionTypeList { Id= "4", FName= "temples" };
new ActionTypeList { Id= "38", FName= "books" };
new ActionTypeList { Id= "28", FName= "stories" };
}
public string Id{ get; set; }
public string FName{ get; set; }
}
我刚举了一个例子,怎么做我不知道。
答案 0 :(得分:2)
如果您需要使用某些数据,那么您将需要在类之外创建不在其中的单独实例,这是一种不好的做法。如果你真的觉得你必须在这个类中有数据,那么添加一个静态方法来获取你的默认内容。
public partial class ActionType
{
public string Id { get; set; }
public string FName { get; set; }
public static IEnumerable<ActionType> GetDefaultActionTypes() {
return new List<ActionType> {
new ActionType { Id = "2", FName = "hanumanji" },
new ActionType { Id = "4", FName = "temples" },
new ActionType { Id = "28", FName = "books" },
new ActionType { Id = "38", FName = "stories" },
};
}
}
然后您可以使用像这样的静态方法
var myDefaultActionTypes = ActionType.GetDefaultActionTypes();
答案 1 :(得分:2)
创建新课程ActionType
并将您的项目存储在ActionTypeList
:
public class ActionType {
public ActionType() {
}
public string Id { get; set; }
public string FName { get; set; }
}
public class ActionTypeList : List<ActionType> {
public ActionTypeList() {
Add(new ActionType() { Id = "2", FName = "hanumanji" });
Add(new ActionType { Id = "4", FName = "temples" });
Add(new ActionType { Id = "38", FName = "books" });
Add(new ActionType { Id = "28", FName = "stories" });
}
}
答案 2 :(得分:1)
您可以在类中定义静态方法
public static List<ActionTypeList> GetActionTypes()
{
return new List<ActionTypeList>
{
new ActionTypeList { Id= "2", FName= "hanumanji" };
new ActionTypeList { Id= "4", FName= "temples" };
new ActionTypeList { Id= "38", FName= "books" };
new ActionTypeList { Id= "28", FName= "stories" };
}
}
无论何时想要获取样本列表,都可以调用此方法。
var list = ActionTypeList.GetActionTypes();