用于开放通用的Automapper自定义转换器

时间:2016-07-25 08:55:29

标签: c# generics automapper

在Automapper中可以映射open generics,但是在尝试将其与自定义类型转换器结合使用时,我遇到了一些问题。

以下

cfg.CreateMap(typeof(IEnumerable<>), typeof(MyCustomCollectionType<>))
.ConvertUsing(typeof(MyConverter));

MyConverter看起来像这样:

class MyConverter : ITypeConverter<object, object>
{
    public object Convert(object source, object destination, ResolutionContext context)
    {
        //... do conversion
    }
}

只会在创建映射时抛出异常:

  

&#39; System.InvalidOperationException&#39;在mscorlib.dll中

     

附加信息:此操作仅对通用类型有效。

如何为开放泛型类型定义自定义类型转换器?我需要实现什么界面?

1 个答案:

答案 0 :(得分:6)

开放式泛型的转换器需要是泛型类型。它看起来像是:

public class MyConverter<TSource, TDest> 
    : ITypeConverter<IEnumerable<TSource>, MyCustomCollectionType<TDest>> {
    public MyCustomCollectionType<TDest> Convert(
        IEnumerable<TSource> source, 
        MyCustomCollectionType<TDest> dest, 
        ResolutionContext context) {
        // you now have the known types of TSource and TDest
        // you're probably creating the dest collection
        dest = dest ?? new MyCustomCollectionType<TDest>();
        // You're probably mapping the contents
        foreach (var sourceItem in source) {
            dest.Add(context.Mapper.Map<TSource, TDest>(sourceItem));
        }
        //then returning that collection
        return dest;
    }
}
相关问题