我的问题与询问的here非常相似,但是我无法根据所提供的答案找到解决方案。我一定错过了指日可待的东西。
我有一个自定义转换器,允许我执行以下操作:
cfg.CreateMap<Container<int>, int>().ConvertUsing(new ContainerConverter<Container<int>, int>());
但是int
不是唯一的类型参数,有一种简洁的表达方式:
cfg.CreateMap<Container<T>, T>().ConvertUsing(new ContainerConverter<Container<T>, T>());
无需执行:
cfg.CreateMap<Container<int>, int>().ConvertUsing(new ContainerConverter<Container<int>, int>());
cfg.CreateMap<Container<long>, long>().ConvertUsing(new ContainerConverter<Container<long>, long>());
...
对于每个正在使用的T
?
在我的情况下,Container<T>
和T
的属性又是类A1, A2...
和B1, B2...
的成员。通过调用
B dest = mapper.Map<A, B>(source);
先谢谢您。
如果您不介意拳击,则可以使用通用转换器。
static void Main(string[] args)
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap(typeof(Container<>), typeof(object)).ConvertUsing(typeof(ContainerConverter<>));
});
config.AssertConfigurationIsValid();
//config.BuildExecutionPlan(typeof(Destination), typeof(Source)).ToReadableString().Dump();
var mapper = config.CreateMapper();
mapper.Map<int>(new Container<int>{ Value = 12 }).Dump();
}
public class ContainerConverter<T> : ITypeConverter<Container<T>, object>
{
public object Convert(Container<T> source, object destination, ResolutionContext c)
{
return source.Value;
}
}
public class Container<T>
{
public T Value { get; set; }
}