我需要将Int32 []转换为IList,其中RoleModel是枚举,我有:
CreateMap<Int32, RoleModel>()
将Int32 []转换为List时,不会应用此选项。所以我试过了:
CreateMap<Int32[], IList<RoleModel>>().ConvertUsing(x => x.Select(y => (RoleModel)y).ToList());
这有效......这不奇怪吗?第一种选择不应该有用吗?
谢谢你, 米格尔
答案 0 :(得分:0)
试试这个有效。
public enum RoleModel
{
None = 0,
RoleModel1 = 1,
RoleModel2 = 2,
RoleModel3 = 3
}
class Program
{
static void Main(string[] args)
{
Mapper.CreateMap<int, RoleModel>().ConvertUsing<IntToEnumConver>();
var roleModel = Mapper.Map<int, RoleModel>(2);
var lstInt = new List<int> { 3, 2, 1 };
var roleModels = Mapper.Map<IList<int>, IList<RoleModel>>(lstInt);
}
}
public class IntToEnumConver : ITypeConverter<int, RoleModel>
{
public RoleModel Convert(ResolutionContext context)
{
var source = context.SourceValue as int?;
if (Enum.IsDefined(typeof(RoleModel), source))
{
return (RoleModel)source;
}
else
{
// Throw exception or Retrun None, etc.
return RoleModel.None;
}
}
}
另外,如果您想在下面使用数组而不是List<T>
。
var lstInt = new[] { 3, 2, 1 };
var roleModels = Mapper.Map<int[], IList<RoleModel>>(lstInt);