2014-05-17 4 views
1

지도 2 Indexer class by AutoMapper? CollectionItem 유형을 사용하는 두 개의 모델을 매핑해야합니다. AutoMapper를 사용하려고했습니다. 그러나 그것은 효과가 없습니다. 아래 예를 참조하십시오.인덱서 클래스 및 AutoMapper C#

감사합니다.

+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(); 
    } 
}