c# – 如何使用泛型创建Fluent界面
作者:互联网
我想创建一个流畅的界面,可以像这样使用:
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;}
}
我无法获得上述功能,但I did create something similar以类似的方式工作,但我并不特别喜欢如何设置流畅的界面.我宁愿让它读起来像我上面的方式.
解决方法:
您可以使用以下代码实现它
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方法调用的通用参数,因为它们将由编译器推断.而且你得到的打字比在各处使用对象更好.
当然这是最简单的版本.您可以在这些类型之间传递更多信息,因为您指定了下一个必要类型的创建方式.
它还调用MapViewModel而不首先调用MapDomainModel(只要你将构造函数设置为内部并在单独的dll中关闭所有内容),这应该是一件好事.
标签:c,expression,fluent-interface,generics 来源: https://codeday.me/bug/20190517/1120662.html