是否可以在 2 个不同的枚举之间进行映射?
也就是说,我想获取一个枚举值并将其映射到不同枚举类型中的相应值。
我知道如何使用 AutoMapper 做到这一点:
// Here's how to configure...
Mapper.CreateMap<EnumSourceType, EnumTargetType>();
// ...and here's how to map
Mapper.Map<EnumTargetType>(enumSourceValue)
但我是 ValueInjecter 的新手,无法弄明白。
** 更新 **
源和目标枚举类型类似于:
public enum EnumSourceType
{
Val1 = 0,
Val2 = 1,
Val3 = 2,
Val4 = 4,
}
public enum EnumTargetType
{
Val1,
Val2,
Val3,
Val4,
}
因此,常量具有相同的名称,但具有不同的值。
最佳答案
好的,解决方案非常简单,我使用约定注入(inject)来按名称匹配属性,并且在我使用 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);
}
关于c# - 使用 ValueInjecter 在枚举之间映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11503941/