簡體   English   中英

Automapper自定義轉換器,用於開放通用

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM