Map between enumerations with ValueInjecter

Is it possible to display between two different enumerations?

That is, I want to take one enum value and match it with the corresponding value in another type of enumeration.

I know how to do this with AutoMapper:

// Here how to configure... Mapper.CreateMap<EnumSourceType, EnumTargetType>(); // ...and here how to map Mapper.Map<EnumTargetType>(enumSourceValue) 

But I am new to ValueInjecter and cannot understand.

** UPDATE **

The source and target enumeration types look something like this:

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

So, constants have the same name but different meanings.

+4
source share
3 answers

ok, the solution is quite simple, I use conditional injection to match properties by name and that they are both listed after using Enum.Parse to translate from a string to 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); } 
+6
source
  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] ) 
0
source

Here is the version using the LoopInjection base class:

 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())); } } 
0
source

All Articles