[英]Map between enums with ValueInjecter
Is it possible to map between 2 different enums? 是否可以在2个不同的枚举之间进行映射?
That is, I want to take one enum value and map it to a corresponding value in a different enum type. 也就是说,我想获取一个枚举值并将其映射到另一枚举类型中的对应值。
I know how to do this with AutoMapper: 我知道如何使用AutoMapper做到这一点:
// Here's how to configure...
Mapper.CreateMap<EnumSourceType, EnumTargetType>();
// ...and here's how to map
Mapper.Map<EnumTargetType>(enumSourceValue)
But I'm new to ValueInjecter and can't figure it out. 但是我是ValueInjecter的新手,无法弄清楚。
** UPDATE ** ** 更新 **
The source and target enum types look something like: 源和目标枚举类型如下所示:
public enum EnumSourceType
{
Val1 = 0,
Val2 = 1,
Val3 = 2,
Val4 = 4,
}
public enum EnumTargetType
{
Val1,
Val2,
Val3,
Val4,
}
So, the constants have the same names, but different values. 因此,这些常数具有相同的名称,但具有不同的值。
ok, the solution is quite simple, I use the convention injection to match the properties by name and the fact that they are both enums after I use Enum.Parse to cast from string to Enum 好的,解决方案非常简单,我使用约定注入按名称匹配属性,并且在使用Enum.Parse从字符串转换为Enum后它们都是枚举的事实
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);
}
enum EnumSourceType
{
Val1 = 0,
Val2 = 1,
Val3 = 2,
Val4 = 4,
}
enum EnumTargetType
{
Targ1,
Targ2,
Targ3,
Targ4,
}
Dictionary<EnumSourceType, EnumTargetType> SourceToTargetMap = new Dictionary<EnumSourceType, EnumTargetType>
{
{EnumSourceType.Val1, EnumTargetType.Targ1},
{EnumSourceType.Val2, EnumTargetType.Targ2},
{EnumSourceType.Val3, EnumTargetType.Targ3},
{EnumSourceType.Val4, EnumTargetType.Targ4},
};
Console.WriteLine( SourceToTargetMap[EnumSourceType.Val1] )
Here's a version using LoopInjection base class: 这是使用LoopInjection基类的版本:
public class EnumsByStringName : LoopInjection
{
protected override bool MatchTypes(Type source, Type target)
{
return ((target.IsSubclassOf(typeof(Enum))
|| Nullable.GetUnderlyingType(target) != null && Nullable.GetUnderlyingType(target).IsEnum)
&& (source.IsSubclassOf(typeof(Enum))
|| Nullable.GetUnderlyingType(source) != null && Nullable.GetUnderlyingType(source).IsEnum)
);
}
protected override void SetValue(object source, object target, PropertyInfo sp, PropertyInfo tp)
{
tp.SetValue(target, Enum.Parse(tp.PropertyType, sp.GetValue(source).ToString()));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.