C# 将类型MyType映射到MyType时出现InvalidCastException

C# 将类型MyType映射到MyType时出现InvalidCastException,c#,generics,automapper,.net-4.5,automapper-2,C#,Generics,Automapper,.net 4.5,Automapper 2,我使用AutoMapper 2.2.1将不同的业务对象映射到视图模型。现在,如果我尝试映射具有类型为CustomList的属性的对象,就会得到一个InvalidCastExceptions(请参见下面的代码)。 例外情况是,CustomList不能强制转换为IList。这是正确的,因为CustomList实现了IReadOnlyList而不是IList 那么,为什么automapper会尝试以这种方式强制转换它,以及如何修复/解决这个问题呢 我有以下几种: 公共类MyViewModel:Some

我使用AutoMapper 2.2.1将不同的业务对象映射到视图模型。现在,如果我尝试映射具有类型为
CustomList
的属性的对象,就会得到一个
InvalidCastExceptions
(请参见下面的代码)。 例外情况是,
CustomList
不能强制转换为
IList
。这是正确的,因为
CustomList
实现了
IReadOnlyList
而不是
IList

那么,为什么automapper会尝试以这种方式强制转换它,以及如何修复/解决这个问题呢

我有以下几种:

公共类MyViewModel:SomeModel{//…一些附加的东西…}
公共类模型{
公共自定义列表描述列表{get;internal set;}
}
公共类CustomList:ReadOnlyList{}
公共抽象类ReadOnlyList:IReadOnlyList{}
//地图
//aList是SomeModel的类型
var viewList=Mapper.Map(列表);

让类从IReadOnlyList实现很可能是导致问题的原因。Automapper不知道如何将只读列表映射到只读列表。它创建对象的新实例,并且没有用于IReadOnlyList的add方法或集合初始值设定项。Automapper需要能够访问只读列表环绕的基础列表。这可以使用ConstructUsing方法完成

更新的列表模型:

public class CustomList : IReadOnlyList<string>
{
    private readonly IList<string> _List;

    public CustomList (IList<string> list)
    {
        _List = list;
    }

    public CustomList ()
    {
        _List = new List<string>();
    }

    public static CustomList CustomListBuilder(CustomList customList)
    {
        return new CustomList (customList._List);
    }
}
public类CustomList:IReadOnlyList
{
私有只读IList_列表;
公共客户列表(IList列表)
{
_列表=列表;
}
公共客户列表()
{
_列表=新列表();
}
公共静态CustomList CustomListBuilder(CustomList CustomList)
{
返回新的CustomList(CustomList.\u List);
}
}
更新的自动映射配置

Mapper.CreateMap<CustomList, CustomList>().ConstructUsing(CustomList.CustomListBuilder);
Mapper.CreateMap().ConstructUsing(CustomList.CustomListBuilder);

这是一个简单的示例,但我能够使它正确映射,并且不会引发异常。这不是最好的代码,这样做会导致同一个列表被两个不同的只读列表引用(取决于您的需求,这可能没问题)。希望这会有所帮助。

ReadOnlyList肯定是导致问题的原因。我用一种也不太干净的溶液来修复它。我使用
new
覆盖并隐藏ViewModel中的ReadOnlyList成员。像这样更改返回类型也不像应该的那样干净。