我有一个为ASP.NET MVC加载大型选择列表的函数。 该函数具有354行的方法。 我想重构更多函数或局部字段,以便每个函数少于40行。
以下是代码段:
public static SelectList CreateShutterSpeedList()
{
var shutterSpeedList = new List<CameraSettingItem>();
var secNotationPostfix = "\"";
shutterSpeedList.Add(new CameraSettingItem
{
Id = ShutterSpeedDefaultValue,
Description = string.Empty
});
shutterSpeedList.Add(new CameraSettingItem
{
Id = 1,
Description = "30" + secNotationPostfix
});
etc
也许私人列表作为变量?或从文件加载?或者......?
答案 0 :(得分:0)
如果按顺序分配ShutterSpeedDefaultValue
以上的ID,您可以先创建一个描述数组,然后使用LINQ将其转换为CameraSettingItem
列表:
var descriptions = new[] {
string.Empty
, "30" + secNotationPostfix
, ...
};
shutterSpeedList = descriptions
.Select((d,i) => new CameraSettingItem {
Id = i==0 ? ShutterSpeedDefaultValue : i
, Description = d
})
.ToList();
您还可以在方法正文之外创建CameraSettingItem
列表,如下所示:
private const string secNotationPostfix = "\"";
private static IList<CameraSettingItem> shutterSpeedList = new List<CameraSettingItem> {
new CameraSettingItem {
Id = ShutterSpeedDefaultValue,
Description = string.Empty
},
new CameraSettingItem {
Id = 1,
Description = "30" + secNotationPostfix
},
...
};
public static SelectList CreateShutterSpeedList() {
return new SelectList(shutterSpeedList, "Id", "Description");
}
答案 1 :(得分:0)
您可以在JSON或XML文件中存储所需的项目,并在需要使用enrich或JavaScriptSerializer时对其进行反序列化,例如:
public static SelectList CreateShutterSpeedList(
{
var json = File.ReadAllText(@"\ShutterSpeedList.json");
var shutterSpeedList = JsonConvert.DeserializeObject<List<CameraSettingItem>>(json);
// Convert shutterSpeedList to SelectList and return
}
或者,如果您可以访问CameraSettingItem
代码,则可以使用集合初始值设定项(如@dasblinkenlight指出)和带有可选参数/对象初始值设定项的构造函数来减少行数:
public static SelectList CreateShutterSpeedList()
{
var secNotationPostfix = "\"";
var shutterSpeedList = new List<CameraSettingItem>
{
new CameraSettingItem(id: ShutterSpeedDefaultValue),
new CameraSettingItem(id: 1, description: "30" + secNotationPostfix),
...
};
// Convert shutterSpeedList to SelectList and return
}