c# - 将一个对象映射到另一个对象的最佳实践

标签 c# design-patterns mapping

我的问题是,以最可维护的方式将一个对象映射到另一个对象的最佳方式是什么。我无法更改我们获取的 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/

相关文章:

python - 计算嵌套列表中的元素

c# - 如何在回调方法中停止 System.Threading.Timer

c# - WPF 中的预测键入功能

c# - 抛出异常 : 'System.Exception' in Alea. dll“i32 不是结构类型

java - 为什么模板方法被标记为final?

c++ - 防止代码死锁的锁定策略和技巧

c# - 在 View 之间传递数据的最佳方式是什么?

javascript - 如何使用不同的名称从模型映射到字段

json - 有没有办法在 Swift 中仅从 JSON 部分创建对象?

c# - Equals 方法在调试和 Release模式下的行为不同