我有以下代码有一些重复
private List<SelectListItem> GetDeskList(int deskId)
{
List<Desk> apps = Model.GetDesks();
List<SelectListItem> dropdown = apps.ConvertAll(c => new SelectListItem
{
Selected = c.Id == deskId,
Text = c.Name,
Value = c.Id.ToString()
}).ToList();
dropdown.Insert(0, new SelectListItem());
return dropdown;
}
private List<SelectListItem> GetRegionList(int regionId)
{
List<Region> apps = Model.GetRegions();
List<SelectListItem> dropdown = apps.ConvertAll(c => new SelectListItem
{
Selected = c.Id == regionId,
Text = c.Name,
Value = c.Id.ToString()
}).ToList();
dropdown.Insert(0, new SelectListItem());
return dropdown;
}
还有一些类似的模式。重构这个以避免重复的最佳方法是什么
答案 0 :(得分:4)
只是在黑暗中刺伤,但这样的事情应该是你应该去的地方:
private List<SelectListItem> GetList<T>(List<T> list, int Id)
{
List<SelectListItem> dropdown = list.ConvertAll(c => new SelectListItem
{
Selected = c.Id == Id,
Text = c.Name,
Value = c.Id.ToString()
}).ToList();
dropdown.Insert(0, new SelectListItem());
return dropdown;
}
并传入您的类型安全列表,而不是调用GetList
方法
答案 1 :(得分:2)
如果您可以更改模型以实现通用接口(或从公共基类继承),那么您可以执行以下操作:
var desks = GetList(123, () => Model.GetDesks());
var regions = GetList(456, () => Model.GetRegions());
// ...
private List<SelectListItem> GetList<T>(int id, Func<List<T>> getApps)
where T : IDropdownItem
{
List<T> apps = getApps();
List<SelectListItem> dropdown = apps.ConvertAll(c => new SelectListItem
{
Selected = c.Id == id,
Text = c.Name,
Value = c.Id.ToString()
}).ToList();
dropdown.Insert(0, new SelectListItem());
return dropdown;
}
public interface IDropdownItem
{
int Id { get; }
string Name { get; }
}
public class Desk : IDropdownItem { /* ... */ }
public class Region : IDropdownItem { /* ... */ }
答案 2 :(得分:1)
private List<SelectListItem> GetObjectList<ObjectType>(int id, Func<List<ObjectType>> getObjects)
{
List<ObjectType> apps = getObjects();
List<SelectListItem> dropdown = apps.ConvertAll(c => new SelectListItem
{
Selected = c.Id == id,
Text = c.Name,
Value = c.Id.ToString()
}).ToList();
dropdown.Insert(0, new SelectListItem());
return dropdown;
}
private List<SelectListItem> GetDeskList(int deskId)
{
return GetObjectList(deskId, (() -> Model.GetDesks()));
}
private List<SelectListItem> GetRegionList(int regionId)
{
return GetObjectList(regionId, (() -> Model.GetRegions()));
}
答案 3 :(得分:0)
可能会对列表项类型的函数进行模板化,并传入列表?
private List<SelectListItem, ItemType> GetRegionList(int theId, List<ItemType> apps)
{
List<SelectListItem> dropdown = apps.ConvertAll(c => new SelectListItem
{
Selected = c.Id == theId,
Text = c.Name,
Value = c.Id.ToString()
}).ToList();
dropdown.Insert(0, new SelectListItem());
return dropdown;
}
List<Desk> apps = Model.GetDesks();
GetRegionList<SelectListItem,Desk>(ID, apps);
答案 4 :(得分:0)
我还强烈建议你看一下Matthew Cochran关于模式的一些博客。我觉得他们真有帮助。这是一个: Visitor pattern只是看看他的一些模式。