C# 自动将枚举映射到枚举类

C# 自动将枚举映射到枚举类,c#,enums,automapper,C#,Enums,Automapper,我正在尝试使用Automapper将常规枚举映射到枚举类(如Jimmy Bogard所述)。常规枚举的值与枚举类的值不同。因此,如果可能的话,我想使用名称进行映射: 枚举: 枚举类: public class ProductType : Enumeration { public static ProductType ProductType1 = new ProductType(8, "Product Type 1"); public static ProductType Prod

我正在尝试使用Automapper将常规枚举映射到枚举类(如Jimmy Bogard所述)。常规枚举的值与枚举类的值不同。因此,如果可能的话,我想使用名称进行映射:

枚举:

枚举类:

public class ProductType : Enumeration
{
    public static ProductType ProductType1 = new ProductType(8, "Product Type 1");
    public static ProductType ProductType2 = new ProductType(72, "Product Type 2");

    public ProductType(int value, string displayName)
        : base(value, displayName)
    {
    }

    public ProductType()
    {
    }
}
任何帮助,使这一绘图工作感谢!我只尝试了常规映射:

Mapper.Map<ProductType, Domain.ProductType>();
Mapper.Map();
。。但映射类型的值为0

谢谢,
Alex

以下是Automapper的工作原理-它获取目标类型的公共实例属性/字段,并将与源类型的公共实例属性/字段相匹配。您的枚举没有公共属性。枚举类有两个值和DisplayName。对于Automapper,没有可映射的内容。您可以使用的最好方法是简单的映射器函数(我喜欢使用扩展方法):

用法:

ProductType productType = ProductType.ProductType1;
var result = productType.ToDomainProductType();
var result = productType.ToEnumeration<ProductType, Domain.ProductType>();
如果您真的想在这种情况下使用Automapper,可以使用映射表达式的方法将此创建方法提供给
Construction:

Mapper.CreateMap<ProductType, Domain.ProductType>()
      .ConstructUsing(Extensions.ToDomainProductType);

更新:您可以使用反射创建在枚举和相应枚举类之间映射的通用方法:

public static TEnumeration ToEnumeration<TEnum, TEnumeration>(this TEnum value)
{
    string name = Enum.GetName(typeof(TEnum), value);
    var field = typeof(TEnumeration).GetField(name);
    return (TEnumeration)field.GetValue(null);
}
public static TEnumeration to numeration(此TEnum值)
{
字符串名称=Enum.GetName(typeof(TEnum),value);
var field=typeof(TEnumeration).GetField(name);
return(TEnumeration)字段.GetValue(null);
}
用法:

ProductType productType = ProductType.ProductType1;
var result = productType.ToDomainProductType();
var result = productType.ToEnumeration<ProductType, Domain.ProductType>();
var result=productType.ToEnumeration();

无论你是谁,对反对票的一些反馈都会很好,谢谢你的解释,我现在理解了问题所在。我想我最终可能会更改枚举,使其具有匹配的值,并映射到枚举类的值实例成员。我比什么都好奇!我认为反射版本相当不错,因此在某些时候可能会派上用场。Thanksher是我最后要做的-如果您确实想从与枚举类具有相同值的枚举映射(我知道的另一个问题)mapper.CreateMap().ConstructUsing(dto=>enumeration.FromValue((int)dto.SourceValue));
var result = productType.ToEnumeration<ProductType, Domain.ProductType>();