[英]Automapper custom converter for open generic
在Automapper中可以映射开放的泛型 ,但是尝试将其与自定义类型转换器结合使用时出现了一些问题。
下列
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.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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.