Indexer Class和AutoMapper C#

时间:2014-05-17 14:07:43

标签: c#-4.0 automapper

如何通过AutoMapper映射2个Indexer类?我需要映射两个属性使用CollectionItem类型的模型。我尝试使用AutoMapper。但它不起作用。请参阅下面的示例索引器类:

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

谢谢!

1 个答案:

答案 0 :(得分: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();
    }
}