gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:19:31 24 4
gpt4 key购买 nike

映射open generics在 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
}
}

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

'System.InvalidOperationException' in mscorlib.dll

Additional information: This operation is only valid on generic types.

如何为开放通用类型定义自定义类型转换器?我需要实现什么接口(interface)?

最佳答案

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

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

关于c# - 用于开放通用的 Automapper 自定义转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38563415/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com