C# Automapper自定义转换器,用于开放式通用

C# Automapper自定义转换器,用于开放式通用,c#,generics,automapper,C#,Generics,Automapper,映射在Automapper中是可能的,但是我在尝试将其与自定义类型转换器结合时遇到了一些问题 以下 cfg.CreateMap(typeof(IEnumerable<>), typeof(MyCustomCollectionType<>)) .ConvertUsing(typeof(MyConverter)); cfg.CreateMap(typeof(IEnumerable)、typeof(MyCustomCollectionType)) .ConvertUsing(

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

以下

cfg.CreateMap(typeof(IEnumerable<>), typeof(MyCustomCollectionType<>))
.ConvertUsing(typeof(MyConverter));
cfg.CreateMap(typeof(IEnumerable)、typeof(MyCustomCollectionType))
.ConvertUsing(类型为(MyConverter));
MyConverter的外观如下:

class MyConverter : ITypeConverter<object, object>
{
    public object Convert(object source, object destination, ResolutionContext context)
    {
        //... do conversion
    }
}
类MyConverter:ITypeConverter
{
公共对象转换(对象源、对象目标、ResolutionContext上下文)
{
//…进行转换
}
}
仅在创建映射时引发异常:

mscorlib.dll中的“System.InvalidOperationException”

其他信息:此操作仅对泛型类型有效


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

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

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;
    }
}
公共类MyConverter
:ITypeConverter{
公共MyCustomCollectionType转换(
IEnumerable来源,
MyCustomCollectionType dest,
决议(上下文){
//现在您有了已知类型的TSource和TDest
//您可能正在创建dest集合
dest=dest??新建MyCustomCollectionType();
//您可能正在映射内容
foreach(源中的var sourceItem){
dest.Add(context.Mapper.Map(sourceItem));
}
//然后把那笔钱还回去
返回目的地;
}
}

如下更新映射并选中,
cfg.CreateMap().ConvertUsing(新的MyConverter())那么这个转换器将为我不打算做的任何事情提供支持。初始化时,它将抛出类型为“System.Object”的表达式,不能用于分配给类型为“System.Double”的表达式。我已经尝试过这个方法,但根本无法让它工作。我总是会遇到一个异常,声明“无法将类型为'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[文档]]]