使用ValueInjecter在枚举之间映射

Coc*_*lla 4 c# enums valueinjecter

是否可以在2个不同的枚举之间进行映射?

也就是说,我想获取一个枚举值并将其映射到不同枚举类型中的相应值.

我知道如何使用AutoMapper执行此操作:

// Here's how to configure...
Mapper.CreateMap<EnumSourceType, EnumTargetType>();

// ...and here's how to map
Mapper.Map<EnumTargetType>(enumSourceValue)
Run Code Online (Sandbox Code Playgroud)

但我是ValueInjecter的新手,无法弄明白.

**更新**

源和目标枚举类型类似于:

public enum EnumSourceType
{
    Val1 = 0,
    Val2 = 1,
    Val3 = 2,
    Val4 = 4,
}

public enum EnumTargetType
{
    Val1,
    Val2,
    Val3,
    Val4,
}
Run Code Online (Sandbox Code Playgroud)

因此,常量具有相同的名称,但值不同.

Omu*_*Omu 6

好吧,解决方案很简单,我使用常规注入来匹配属性的名称,以及在我使用Enum.Parse从字符串转换为枚举后它们都是枚举的事实

public class EnumsByStringName : ConventionInjection
{
    protected override bool Match(ConventionInfo c)
    {
        return c.SourceProp.Name == c.TargetProp.Name 
            && c.SourceProp.Type.IsEnum 
            && c.TargetProp.Type.IsEnum;
    }

    protected override object SetValue(ConventionInfo c)
    {
        return Enum.Parse(c.TargetProp.Type, c.SourceProp.Value.ToString());
    }
}

public class F1
{
    public EnumTargetType P1 { get; set; }
}

[Test]
public void Tests()
{
    var s = new { P1 = EnumSourceType.Val3 };
    var t = new F1();
    t.InjectFrom<EnumsByStringName>(s);

    Assert.AreEqual(t.P1, EnumTargetType.Val3);
}
Run Code Online (Sandbox Code Playgroud)