如何清理这段代码以消除重复?
我有以下代码,其中有一些重复
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;
}
,还有一些类似的代码具有类似的模式。重构以避免重复的最佳方法是什么
i have the following code which has some duplication
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;
}
and a few more like it with a similar pattern. what is the best way to refactor this to avoid duplication
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
只是在黑暗中刺探,但您应该这样做:
并传入类型安全列表,而不是调用
GetList
方法中的方法Just a stab in the dark, but something like this is where you should head:
and pass in your type safe lists instead of calling the methods in the
GetList
method如果您可以更改模型以实现公共接口(或从公共基类继承),那么您可能可以执行以下操作:
If you can change your models to implement a common interface (or inherit from a common base class) then you might be able to do something like this:
也许将列表项类型上的函数模板化,然后传入列表?
Maybe templatize the function on the list item type, and pass in the list?
我还强烈建议您查看 Matthew Cochran 的一些关于模式的博客。我发现它们真的很有帮助。这是一个:
访客模式,只需在他的帖子下查看一些他的模式。
I would also strongly suggest you have a look at some of Matthew Cochran's blogs on patterns. I found them really helpful. Here is one:
Visitor pattern and just look under his posts for a few of his patterns.