c# - 映射容器使用 AutoMapper 到 T
问题描述
我的问题与此处提出的问题非常相似,但我无法根据提供的答案找到解决方案。我一定是错过了一些就在拐角处的东西。
我有一个自定义转换器,允许我执行以下操作:
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; }
}
推荐阅读
- php - 试图在codeigniter中制作基本网址
- ios - 如何使用 Codable 处理 JSON 响应失败的情况?
- excel - 如何应用 IsMissing 功能?
- javascript - 如何成功地将 laravel 代码库迁移或转移到新的 laravel 脚手架
- matlab - 当提供足够的输入参数时,matlab 是否有解决方案声称输入参数不足?
- jenkins - 如何通过jenkins启动webdriver manager
- prometheus - 具有不同帮助文本的 Prometheus 指标的含义?
- delphi - Delphi ORD函数未返回预期值
- java - 如何绘制 2 个城市之间的距离(关系 JPA)
- magento2 - 我在我的块中使用 \Magento\Customer\Model\SessionFactory $customerSession 但如果没有可缓存的 false 它就无法工作