4

Is it possible to map between 2 different enums?

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:

// 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.

** 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.

4

3 回答 3

6

好的,解决方案很简单,我使用约定注入来按名称匹配属性,并且在我使用 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);
}
于 2012-07-17T20:27:04.487 回答
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] )
于 2015-04-15T08:46:11.287 回答
-1

这是使用 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()));
        }
    }
于 2017-01-09T22:59:16.240 回答