Skip to main content
 首页 » 编程设计

c#之Automapper (5.1.1) ForAllMembers之获取当前属性的名称

2024年02月05日29davidwang456

这是我的问题,在 Condition 中,我想获取正在评估的当前属性的名称。我相信您可以在早期版本的 Automapper 中执行此操作。有什么建议吗?

[TestFixture] 
public class SandBox 
{ 
    public class MySource 
    { 
        public string Name { get; set; } 
        public int Count { get; set; } 
    } 
 
    public class MyDestination 
    { 
        public string Name { get; set; } 
        public int Count { get; set; } 
    } 
 
    public class SourceProfile : Profile 
    { 
        public SourceProfile() 
        { 
            this.CreateMap<MySource, MyDestination>() 
                .ForAllMembers(x => x.Condition((source, destination, arg3, arg4, resolutionContext) => 
                { 
                    // this will run twice (once for every property) 
                    // but how can I find out, what the current property is? 
 
                    return true; 
                })); 
        } 
    } 
 
    public SandBox() 
    { 
        Mapper.Initialize(x => 
        { 
            x.AddProfile(new SourceProfile()); 
        }); 
    } 
 
    [Test] 
    public void Run() 
    { 
        var s = new MySource { Name = "X", Count = 42 }; 
        var r = Mapper.Map<MyDestination>(s); 
        Assert.AreEqual(s.Name, r.Name); 
    } 
} 

请您参考如下方法:

尝试以下操作:

this.CreateMap<MySource, MyDestination>() 
            .ForAllMembers(x => x.Condition((source, destination, arg3, arg4, resolutionContext) => 
            { 
                // this will run twice (once for every property) 
                // but how can I find out, what the current property is? 
 
                Debug.WriteLine($"Mapping to {destination.GetType().Name}.{x.DestinationMember.Name}"); 
 
                return true; 
            }));