AutoMapper无法使用协变接口

时间:2018-11-08 22:35:48

标签: c# automapper covariance

using AutoMapper;

namespace MapTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Mapper.Initialize(cfg =>
            {
                cfg.CreateMap<X, Interf<object>>()
                    .ForMember(dest => dest.B, opt => opt.MapFrom(src => src.K))
                    .ForMember(dest => dest.A, opt => opt.Ignore());
            });

            X x = new X { K = 1 };
            Interf<object> instance = new Cl<Y> { A = new Y() };
            Mapper.Map(x, instance);
        }
    }

    class Cl<T> : Interf<T>
    {
        public T A { get; set; }
        public int B { get; set; }
    }

    interface Interf<out T>
    {
        T A { get; }
        int B { get; set; }
    }

    class X
    {
        public int K { get; set; }
    }

    class Y
    {
    }
}

此代码将在Mapper.Map(x, instance)处引起异常,因为即使我给了Automapper一个AutoMapper似乎无法找到用于映射到X -> Interf<object>对象的Cl<Y>映射。提示instance的类型确实为Interf<object>。如果我将CreateMap行更改为:

cfg.CreateMap<X, Interf<Y>>()

它不再崩溃,因为它可以将Cl<Y>解析为Interf<Y>

有什么办法可以解决这个问题?

0 个答案:

没有答案