【问题标题】:Datatype of DTO ClassDTO 类的数据类型
【发布时间】:2018-09-24 11:58:32
【问题描述】:

数据传输对象(DTO)类中属性的数据类型应该是什么? 例如:我的域类可能是:

class Product { 
    string name; 
    decimal price;
    double quantity;
}

我可以像这样创建和使用通用 DTO:

class ProductDTO {
    object name;
    object price;
    object quantity;
}

以便可以将 DTO 发送到不同的 Datalayers 进行 db 映射(oracle sql 或任何其他 db)。

【问题讨论】:

    标签: c# domain-driven-design dto


    【解决方案1】:

    不要这样做。有什么好处?

    您的 DTO 类的用户不知道字段/属性的类型。他大概能猜到Name字段应该是字符串,但是价格和数量呢?他们是双打吗?小数点?整数?

    显然他可以把任何东西放在那里,它会编译和运行,但是你必须检查数据层中的类型并在类型不匹配时抛出异常(如果你不这样做,你的数据库可能会) .

    也许你可以改用泛型,比如

    class ProductDTO<Nt, Pt, Qt>
    {
        Nt name;
        Pt price;
        Qt quantity;
        public ProductDTO(Nt name, Pt price, Qt quantity)
        {
             this.name = name;
             this.price = price;
             this.quantity = quantity;
        }
    }
    

    然后:

    var dto1 = new ProductDTO<string, decimal, double>("product1", 12.3m, 33.0); // name is string, price is decimal, quantity is double
    var dto2 = new ProductDTO<string, double, int>("product2", 122.4, 15);  // string, double, int
    

    您还可以创建一个静态方法和类,让类型推断来完成这项工作:

    static class ProductDTO
    {
        public static ProductDTO<N, P, Q> Create<N, P, Q>(N name, P price, Q quantity)
        {
            return new ProductDTO<N, P, Q>(name, price, quantity);
        }
    }
    

    然后

    var dto3 = ProductDTO.Create("product3", 123.4, 56.7);
    

    【讨论】:

      猜你喜欢
      • 2012-12-05
      • 2018-12-03
      • 2019-02-01
      • 1970-01-01
      • 2013-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多