gpt4 book ai didi

Automapper - 数组的具体对象

转载 作者:行者123 更新时间:2023-12-03 09:45:13 26 4
gpt4 key购买 nike

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

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

但是我得到这个错误:

Using mapping configuration for Employee to System.Int32[] Exception of type 'AutoMapper.AutoMapperMappingException' was thrown. ----> System.NullReferenceException : Object reference not set to an instance of an object.

有什么线索可以用 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]));

}

关于Automapper - 数组的具体对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6179903/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com