2014-05-17 34 views
1

如何通過AutoMapper映射2索引器類?我需要映射兩個具有屬性使用CollectionItem類型的模型。我試圖使用AutoMapper。但它不起作用。請參閱下面的示例索引器類:Indexer類和AutoMapper C#

public class CollectionItem 
{ 
    private readonly IEnumerable<string> _keys; 
    private readonly IDictionary<string, IList<Item>> _relatedContents; 
    private static readonly IList<Item> _emptyList = new List<Item>(); 

    public CollectionItem(IEnumerable<string> keys) 
    { 
     _keys = keys; 
     _relatedContents = new Dictionary<string, IList<Item>>(); 
    } 

    public IList<Item> this[string key] 
    { 
     get 
     { 
      if (!ContainsKey(key)) 
      { 
       throw new KeyNotFoundException("The given key was not present in the dictionary"); 
      } 
      return _relatedContents.ContainsKey(key) ? _relatedContents[key] : _emptyList; 
     } 
    } 

    public bool ContainsKey(string key) 
    { 
     return !string.IsNullOrEmpty(key) && _keys.Contains(key, StringComparer.OrdinalIgnoreCase); 
    } 
} 

謝謝!

+0

*您是怎麼*嘗試使用AutoMapper和*如何*這是不是工作? –

回答

0

您可以編寫自己的自定義類型解析:

class FromCollection 
{ 
    private List<string> _items; 

    public int Count 
    { 
     get { return _items.Count; } 
    } 
    public string this[int index] 
    { 
     get { return _items[index]; } 
     set { 
      _items[index] = value; 
     } 
    } 

    public FromCollection() 
    { 
     _items = new List<string>(Enumerable.Repeat("", 10)); 
    } 
} 

class ToCollection 
{ 
    private List<string> _items; 

    public string this[int index] 
    { 
     get { return _items[index]; } 
     set { 
      _items[index] = value; 
     } 
    } 

    public ToCollection() 
    { 
     _items = new List<string>(Enumerable.Repeat("", 10)); 
    } 
} 

class IndexerTypeConverter : TypeConverter<FromCollection, ToCollection> 
{ 
    protected override ToCollection ConvertCore(FromCollection source) 
    { 
     ToCollection result = new ToCollection(); 

     for (int i = 0; i < source.Count; i++) 
     { 
      result[i] = source[i]; 
     } 

     return result; 
    } 
} 

internal class Program 
{ 
    private static void Main(string[] args) 
    { 
     Mapper.CreateMap<FromCollection, ToCollection>() 
      .ConvertUsing<IndexerTypeConverter>(); 

     var src = new FromCollection(); 
     src[3] = "hola!"; 

     var dst = Mapper.Map<ToCollection>(src); 
     Console.WriteLine(); 
    } 
}