如何使用值注入器映射枚举

How to map enums using Value Injector

我正在尝试使用过去使用过 Automapper 的 ValueInjector。我想将一个枚举转换为另一个枚举,其中只有枚举名称不同但 属性 名称和值相同。

 public enum GenderModel
    {
        NotSpecified = 0,
        Male = 1,
        Female = 2
    }

public enum GenderDto
    {
        NotSpecified = 0,
        Male = 1,
        Female = 2
    }

然后我尝试这样映射

var model = GenderModel.Male;
            var dto = GenderDto.NotSpecified;
            dto.InjectFrom(model);

我希望在 dto 对象中得到 Male,但它仍然设置为 NotSpecified。

我错过了什么?请指导。

在我看来,ValueInjecter不能映射enum, struct, int, double等值类型。或者不需要映射值类型。它只有助于映射具有相同名称和类型的 class 类型的属性。要为这个例子映射枚举,我建议,

    var model = GenderModel.Male;
    var dto = GenderDto.NotSpecified;
    dto = (GenderDto)model;

如果枚举嵌套在特定的 class 中,默认的 ValueInjecter 无法映射 GenderModelGenderDto,因为它们是不同的类型。所以我们可以通过一个客户ValueInjecter来实现。这是我的测试代码,希望对你有帮助。

public enum GenderModel
{
    NotSpecified = 0,
    Male = 1,
    Female = 2
}

public enum GenderDto
{
    NotSpecified = 0,
    Male = 1,
    Female = 2
}

public class Person1
{
    public GenderModel Gender { get; set; }
}

public class Person2
{
    public GenderDto Gender { get; set; }
}

public class EnumMapInjection:IValueInjection
{
    public object Map(object source, object target)
    {
        StaticValueInjecter.DefaultInjection.Map(source, target);
        if (target is Person2 && source is Person1)
        {
            ((Person2) target).Gender = (GenderDto)((Person1) source).Gender;
        }
        return target;
    }
}

主要功能代码:

    static void Main(string[] args)
    {
        var person1 = new Person1(){Gender = GenderModel.Male};
        var person2 = new Person2(){Gender = GenderDto.Female};
        person2.InjectFrom<EnumMapInjection>(person1); 
    }

类型转换是您的解决方案

dto = (GenderDto)model;