我想创建一个可以像这样使用的流畅接口:
void Main() {
ModelStateMappings.MapDomainModel<Book>().MapViewModel<BookViewModel>()
.Properties(book => book.Author, vm => vm.AuthorsName)
.Properties(book => book.Price, vm => vm.BookPrice);
ModelStateMappings.MapDomainModel<Store>().MapViewModel<StoreViewModel>()
.Properties(store => store.Owner, vm => vm.OwnersName)
.Properties(store => store.Location, vm => vm.Location);
}
我想结束一个看起来像这样的集合:
static class ModelStateaMappings {
private static IList<ModelMappings> mappings;
// other methods in here to get it working
}
class ModelMappings {
public Type DomainModelType {get;set;}
public Type ViewModelType {get;set;}
public IList<PropertyMapping> PropertyMappings {get;set;}
}
class PropertyMapping {
public Expression<Func<object, object>> DomainProperty {get;set;}
public Expression<Func<object, object>> ViewModelProperty {get;set;}
}
我无法完成上述工作,但是确实创建了类似的东西,并且以类似的方式工作,但是我并不特别喜欢必须设置流畅的界面。我宁愿像上面一样阅读它。
您可以使用以下代码来实现
static class ModelStateMappings
{
public static DomainModelMapping<TDomainModel> MapDomainModel<TDomainModel>()
{
// edit the constructor to pass more information here if needed.
return new DomainModelMapping<TDomainModel>();
}
}
public class DomainModelMapping<TDomainModel>
{
public ViewModelMapping<TDomainModel, TViewModel> MapViewModel<TViewModel>()
{
// edit the constructor to pass more information here if needed.
return new ViewModelMapping<TDomainModel, TViewModel>();
}
}
public class ViewModelMapping<TDomainModel, TViewModel>
{
public ViewModelMapping<TDomainModel, TViewModel>
Properties<TDomainPropertyType, TViewModelPropertyType>(
Expression<Func<TDomainModel, TDomainPropertyType>> domainExpr,
Expression<Func<TViewModel, TViewModelPropertyType>> viewModelExpr)
{
// map here
return this;
}
}
您不必指定所有先前设置的通用类型,因为它们已经被记住为返回类型的通用参数。Properties
可以跳过方法调用的通用参数,因为它们将由编译器推断出来。与在object
任何地方使用s相比,您得到的打字效果更好。
当然,这是最简单的版本。您可以在这些类型之间传递更多的信息,因为您指定了如何创建下一个必需的类型。
它还使调用MapViewModel
而不MapDomainModel
首先调用成为不可能(一旦您使构造函数internal
并在单独的dll中关闭所有内容),那应该是一件好事。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句