2016-07-25 77 views
1

映射open generics是可能的自动映射器,但我已经accros一些问题试图将它与自定义类型转换器相结合。自动映射器自定义转换器开放通用

以下

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 
    } 
} 

不随便扔,如果映射会创建一个例外:在mscorlib程序

'System.InvalidOperationException' .dll

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

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

+0

更新如下映射和检查, 'cfg.CreateMap <对象,对象>()ConvertUsing(新MyConverter());' – Thennarasan

+0

那么这个转换器将踢的。关于一切不是我的意图。在初始化时它会抛出_类型为'System.Object'的表达式不能用于赋值来键入'System.Double'_。 – Sjoerd222888

回答

4

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

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; 
    } 
} 
+0

我试过这个,不能让它工作。我总是会收到一个异常,指出“无法投射类型为'RestDataConverter'2 [System.Collections.Generic.List'1 [DocumentRecord],System.Collections.Generic.List'1 [TDocument]]'的对象来键入'AutoMapper。 ITypeConverter'2 [RestData'1 [System.Collections.Generic.List'1 [DocumentRecord]],RestData'1 [System.Collections.Generic.List'1 [Document]]]'。“ – Ristogod