如何编写C#Extension方法将Domain Model对象转换为Interface对象?

Zac*_*ott 5 asp.net-mvc domain-driven-design selectlist selectlistitem

当您有一个需要显示为接口控件的域对象时,如下拉列表,ifwdev建议创建一个扩展方法来添加.ToSelectList().

原始对象是具有与下拉列表的.Text和.Value属性相同的属性的对象列表.基本上,它是SelectList对象的List,而不是同一个类名.

我想你可以使用反射将域对象转换为接口对象.任何人对C#代码都有任何建议吗?SelectList是SelectListItem的MVC下拉列表.

当然,想法是在视图中做这样的事情:

<%= Html.DropDownList("City", 
         (IEnumerable<SelectListItem>) ViewData["Cities"].ToSelectList() )
Run Code Online (Sandbox Code Playgroud)

Rob*_*vey 4

制作物体SelectList的一部分更容易ViewModel

无论如何,您只需循环遍历IEnumerable并将每个项目添加到一个新SelectList对象并返回它。

public static List<SelectListItem> ToSelectList<T>(this IEnumerable<T> enumerable, Func<T, string> text, Func<T, string> value, string defaultOption) 
{ 
    var items = enumerable.Select(f => new SelectListItem() { Text = text(f), Value = value(f) }).ToList(); 
    items.Insert(0, new SelectListItem() { Text = defaultOption, Value = "-1" }); 
    return items; 
} 
Run Code Online (Sandbox Code Playgroud)

如何将这两种类似的方法重构为一种?

  • +1 在视图模型中包含格式化的选择列表数据。它更容易测试,也更容易。 (2认同)