我的问题是,以最可维护的方式将一个对象映射到另一个对象的最佳方式是什么。我无法更改我们获取的 Dto 对象的设置方式以使其更加规范化,因此我需要创建一种方法将其映射到我们对其对象的实现。
这是展示我需要发生什么的示例代码:
class Program
{
static void Main(string[] args)
{
var dto = new Dto();
dto.Items = new object[] { 1.00m, true, "Three" };
dto.ItemsNames = new[] { "One", "Two", "Three" };
var model = GetModel(dto);
Console.WriteLine("One: {0}", model.One);
Console.WriteLine("Two: {0}", model.Two);
Console.WriteLine("Three: {0}", model.Three);
Console.ReadLine();
}
private static Model GetModel(Dto dto)
{
var result = new Model();
result.One = Convert.ToDecimal(dto.Items[Array.IndexOf(dto.ItemsNames, "One")]);
result.Two = Convert.ToBoolean(dto.Items[Array.IndexOf(dto.ItemsNames, "Two")]);
result.Three = dto.Items[Array.IndexOf(dto.ItemsNames, "Three")].ToString();
return result;
}
}
class Dto
{
public object[] Items { get; set; }
public string[] ItemsNames { get; set; }
}
class Model
{
public decimal One { get; set; }
public bool Two { get; set; }
public string Three { get; set; }
}
我认为如果我有某种映射器类可以接受模型对象 propertyInfo、我想转换成的类型以及我想提取的“itemname”,那就太棒了。有没有人有任何建议来使它更清洁?
谢谢!
最佳答案
我会选择 AutoMapper ,一个开源和免费的映射库,它允许根据约定将一种类型映射到另一种类型(即映射具有相同名称和相同/派生/可转换类型的公共(public)属性,以及许多其他 smart ones )。非常容易使用,会让你达到这样的目的:
Model model = Mapper.Map<Model>(dto);
不确定您的具体要求,但 AutoMapper 也支持 custom value resolvers ,这应该可以帮助您编写特定映射器的单个通用实现。
关于c# - 将一个对象映射到另一个对象的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16118085/