将容器 使用自动映射器映射到T

问题描述 投票:-1回答:1

我的问题与询问的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);

先谢谢您。

c# automapper
1个回答
0
投票

如果您不介意拳击,则可以使用通用转换器。

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; }
}
© www.soinside.com 2019 - 2024. All rights reserved.