具体对象到数组

我需要将一些值从一个类映射到一个数组。 例如:

    public class Employee
    {
        public string name;
        public int age;
        public int cars;
    }

必须转换为

[age, cars]

我试过这个

var employee = new Employee()
        {
            name = "test",
            age = 20,
            cars = 1
        };

        int[] array = new int[] {};

        Mapper.CreateMap<Employee, int[]>()
            .ForMember(x => x,
                options =>
                {
                    options.MapFrom(source => new[] { source.age, source.cars });
                }
            );

        Mapper.Map(employee, array);

但我得到这个错误:

使用Employee的映射配置到System.Int32 []抛出了类型'AutoMapper.AutoMapperMappingException'的异常。 ----> System.NullReferenceException:未将对象引用设置为对象的实例。

任何线索用AutoMapper解决这个问题?


我找到了一个好的解决方案 使用ConstructUsing功能即可。

    [Test]
    public void CanConvertEmployeeToArray()
    {

        var employee = new Employee()
        {
            name = "test",
            age = 20,
            cars = 1
        };

        Mapper.CreateMap<Employee, int[]>().ConstructUsing(
                x => new int[] { x.age, x.cars }
            );

        var array = Mapper.Map<Employee, int[]>(employee);

        Assert.That(employee.age, Is.EqualTo(array[0]));
        Assert.That(employee.cars, Is.EqualTo(array[1]));

    }
链接地址: http://www.djcxy.com/p/37399.html

上一篇: concrete object to array

下一篇: Make AutoMapper automatically map prefixed properties