将序列映射到数组时,Automapper返回对同一对象的引用 [英] Automapper returns reference to the same object when mapping sequences to arrays

查看:91
本文介绍了将序列映射到数组时,Automapper返回对同一对象的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个IEnumerable<T>的扩展方法,该方法映射序列项并返回一个克隆数组:

I have an extension method for IEnumerable<T>, which maps sequence items and returns an array of clones:

public static class AutoMapperExtensions
{
    public static T[] MapToArray<T>(this IEnumerable<T> sequence)
    {
        return Mapper.Map<T[]>(sequence);
    }
}

这是代码示例,从我的角度来看,其行为很奇怪:

Here's code sample, whose behavior is weird from my point:

        Mapper.CreateMap<SomeClass, SomeClass>();
        Mapper.AssertConfigurationIsValid();

        // clone list members and store them into array
        var list = new List<SomeClass>
        {
            new SomeClass { MyProperty = 1 },
            new SomeClass { MyProperty = 2 },
        };

        // works fine
        var array = list.MapToArray();

        // let's map array again
        var newArray = array.MapToArray();

        // ...and ensure, that new array was created;
        // this fails, because Automapper returns reference to the same array
        Debug.Assert(array != newArray); 

在我看来,最后的结果是错误的.正如我所期望的那样,该映射器将创建新的克隆数组,它只会将引用返回给同一数组.

It seems to me, that last result is wrong. While I'm expecting, that mapper will create new array of clones, it just returns the reference to the same array.

这是在其他地方记录的还是错误?

Is this documented elsewhere or this is a bug?

推荐答案

所以这不是一个错误-当AutoMapper看到两个可分配的对象时,它将简单地分配它们.如果要覆盖该行为,请在两种集合类型之间创建一个映射.

So this isn't a bug - when AutoMapper sees two objects that are assignable, it will simply assign them. If you want to override that behavior, create a map between the two collection types.

这篇关于将序列映射到数组时,Automapper返回对同一对象的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆