某些背景:这仅仅是我第一次玩"Password confirmation"
对象,并试图简化我可能在我们的一个应用程序中使用的对象。我从事C#开发人员已超过10年,但直到现在再也没有理由跳进表达式中。
我正在尝试生成扩展方法来修改表达式的返回值。更具体地说,我正在尝试添加在创建AutoMapper映射时要使用的扩展方法。
示例地图:
Expression
我想做的就是创建一个扩展方法,这样我就不必在各处map.CreateMap<Widget, WidgetModel>()
.ForMember(x => x.Count, opts => opts.MapFrom(src => src.Count + 1));
进行编写,而只需将其写为:
+ 1
让map.CreateMap<Widget, WidgetModel>()
.Increment(x => x.Count, src => src.Count);
为我做Increment()
。
我四处张望,以至于意识到+ 1
可能是我所需要的,但是我不确定从那里去哪里?
这个the documentation看起来很相似,但是我无法将其转换为我的用例。
答案 0 :(得分:1)
您可以使用Expression.Increment
而不是+ 1。
或者我们可以使其真正通用。
类似这样的东西:
void Main()
{
var mapperConfiguraiton =
new MapperConfiguration(cfg =>
cfg.CreateMap<Widget, WidgetModel>()
.Increment(x => x.CountD, src => src.Count)
.ToUpper(x => x.Name, src=>src.Name));
var widget = new Widget {Count = 3, Name="Jimmy"};
var mapper = mapperConfiguraiton.CreateMapper();
var model = mapper.Map<WidgetModel>(widget);
}
public class Widget {
public int Count {get; set;}
public string Name {get;set;}
}
public class WidgetModel {
public int Count {get; set;}
public string Name {get;set;}
}
public static class MapperExtensions {
public static IMappingExpression<TSource, TDestination> Increment<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression,
Expression<Func<TDestination, int>> destinationMember,
Expression<Func<TSource, int>> sourceMember)
{
return expression.CustomAction(destinationMember, sourceMember, s => s + 1);
}
public static IMappingExpression<TSource, TDestination> ToUpper<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression,
Expression<Func<TDestination, string>> destinationMember,
Expression<Func<TSource, string>> sourceMember)
{
return expression.CustomAction(destinationMember, sourceMember, s => s.ToUpper());
}
public static IMappingExpression<TSource, TDestination> CustomAction<TSource, TDestination, TDestinationMember, TSourceMember>(
this IMappingExpression<TSource, TDestination> expression,
Expression<Func<TDestination, TDestinationMember>> destinationMember,
Expression<Func<TSource, TSourceMember>> sourceMember,
Expression<Func<TSourceMember, TDestinationMember>> transform)
{
var sourceMemberExpression = (MemberExpression)sourceMember.Body;
var sourceParameter = Expression.Parameter(typeof(TSource));
var expr = Expression.Invoke(transform,
Expression
.MakeMemberAccess(sourceParameter, sourceMemberExpression.Member));
var lambda = (Expression<Func<TSource,TSourceMember>>)
Expression.Lambda(expr, sourceParameter);
var newExpression = expression.ForMember(
destinationMember,
opts => opts.MapFrom(lambda));
return newExpression;
}
}
输出:
widget.Count = 3
widget.Name = "Jimmy"
model.Count = 4
model.Name = "JIMMY"