簡體   English   中英

使用ValueInjecter在枚舉之間進行映射

[英]Map between enums with ValueInjecter

是否可以在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,
}

因此,這些常數具有相同的名稱,但具有不同的值。

好的,解決方案非常簡單,我使用約定注入按名稱匹配屬性,並且在使用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] )

這是使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM