重构为更小的功能,如何?

Refactor to smaller function, how?

我有一个函数可以为 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

也许私人列表作为变量?还是从文件加载?否则...?

如果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");
}

您可以将需要的项目存储在 JSON 或 XML 文件中,并在需要时反序列化它们 JavaScriptSerializer or Json.NET 例如:

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 指出的那样)和带有可选 parameters/object 初始化程序的构造函数来减少行数:

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
}