如何使用AutoMapper按照类中定义的顺序映射对象? [英] How to use AutoMapper to map objects by order defined in the class?
问题描述
给出这两个对象(我用一个非常不同的对象来阐明):
Given this two objects (I use a very different objects to clarify better):
public class Car
{
public string Brand {get;set;}
public int Speed {get;set;}
}
public class Apple
{
public string Variety {get;set;}
public int Production {get;set;}
}
AutoMapper
定义了projection
,该projection
允许使用其他名称映射属性:
AutoMapper
defines the projection
that allows mapping properties with different name:
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Car, Apple>()
.ForMember(dest => dest.Variety, opt => opt.MapFrom( src => src.Brand))
.ForMember(dest => dest.Production, opt => opt.MapFrom(src => src.Speed))
});
这应该可以,但是:
是否可以按照类中定义的顺序直接映射这些属性?:
Is there any way to map directly the properties in the order they are defined in the class?:
Brand -> Variety
Speed -> Production
我正在使用 AutoMapper 4.2.1
推荐答案
否.您所描述的顺序"就是它们在C#源代码中的表达方式.请记住,.NET会编译为中间语言(IL),然后由.NET运行时执行.无法保证您将字段键入C#的顺序将与编译为IL时发出的顺序相同.
No. The "order" you're describing is simply how they are expressed in your C# source code. Remember, .NET compiles down to intermediate language (IL) which is then executed by the .NET Runtime. There's no way to guarantee that the order you typed your fields into C# will be the same order they are emitted when compiled into IL.
这篇关于如何使用AutoMapper按照类中定义的顺序映射对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!