using AutoMapper;
public class Source
{
public int Value { get; set; }
}
public class Destination
{
public string Result { get; set; }
}
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap()
.ForMember(dest => dest.Result, opt => opt.MapFrom(src => src.Value))
.ForCondition((src, dest, context) => src.Value > 0); // 使用参数作为映射条件
}
}
public class Program
{
public static void Main()
{
// 创建 AutoMapper 的配置对象并添加映射配置
var config = new MapperConfiguration(cfg => {
cfg.AddProfile();
});
// 构建映射器
var mapper = config.CreateMapper();
// 创建源对象
var source = new Source { Value = 10 };
// 进行映射
var destination = mapper.Map(source);
// 输出结果
Console.WriteLine(destination.Result); // 结果为 "10"
}
}
在上面的示例中,我们定义了一个源类 Source 和一个目标类 Destination。然后,我们创建了一个名为 MappingProfile 的映射配置类,并在其中使用了 ForCondition 方法来设置映射条件。在这个例子中,我们将映射条件设置为源对象的 Value 属性大于 0。最后,我们使用配置对象创建映射器,并使用映射器将源对象映射到目标对象。最后,我们输出了目标对象的 Result 属性,该属性被映射为源对象的 Value 属性的字符串表示。