2012-07-16 89 views
4

是否可以映射2個不同的枚舉?枚舉與ValueInjecter之間的映射

也就是說,我想獲取一個枚舉值並將其映射到不同枚舉類型中的對應值。

我知道如何與AutoMapper做到這一點:

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

// ...and here's how to map 
Mapper.Map<EnumTargetType>(enumSourceValue) 

但我是新來的ValueInjecter並不能弄明白。

** UPDATE **

源和目標枚舉類型類似於:

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

public enum EnumTargetType 
{ 
    Val1, 
    Val2, 
    Val3, 
    Val4, 
} 

所以,常數具有相同的名稱,但不同的值。

+0

大小相同的枚舉?你想要的值只是作爲e1 - > int - > e2? – Omu 2012-07-17 14:01:27

+0

它們都使用'int'作爲基礎類型。兩個枚舉類型中的字符串名稱相同,但整數值不同。 – Cocowalla 2012-07-17 14:51:36

回答

6

ok了,解決的辦法很簡單,我用的是約定注入,他們都枚舉以匹配名稱的屬性,事實上我用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); 
} 
+0

它看起來像你包裝在一個類的枚舉 - 是否有可能直接做我的AutoMapper示例中的映射? – Cocowalla 2012-07-18 06:44:56

+0

EnumsByStringName是valueinjection,這是valueinjeter的工作方式,當你需要做一些自定義的東西時,你創建一個valuinjection並使用它;您可能會注意到valueinjection不是特定於某些類型的,它將與任何枚舉一起使用 – Omu 2012-07-18 08:16:39

0
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

下面是使用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())); 
     } 
    }