DTO 的数据类型 Class
Datatype of DTO Class
数据传输对象 (DTO) Classes 中属性的数据类型应该是什么?
例如:我的域 Class 可能是:
class Product {
string name;
decimal price;
double quantity;
}
我可以像这样创建和使用通用 DTO 吗:
class ProductDTO {
object name;
object price;
object quantity;
}
以便可以将 DTO 发送到不同的数据层以进行数据库映射(oracle sql 或任何其他数据库)。
不要这样做。有什么好处?
您的 DTO class 的用户不知道 fields/properties 的类型。他大概能猜到Name字段应该是string,但是price和quantity呢?他们是双打吗?小数点?整数?
显然他可以把任何东西放在那里,它会编译并运行,但是你必须检查数据层中的类型并在类型不匹配时抛出异常(如果你不,您的数据库可能会)。
也许你可以改用泛型,比如
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
您还可以创建静态方法和 class 并让类型推断完成工作:
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);
数据传输对象 (DTO) Classes 中属性的数据类型应该是什么? 例如:我的域 Class 可能是:
class Product {
string name;
decimal price;
double quantity;
}
我可以像这样创建和使用通用 DTO 吗:
class ProductDTO {
object name;
object price;
object quantity;
}
以便可以将 DTO 发送到不同的数据层以进行数据库映射(oracle sql 或任何其他数据库)。
不要这样做。有什么好处?
您的 DTO class 的用户不知道 fields/properties 的类型。他大概能猜到Name字段应该是string,但是price和quantity呢?他们是双打吗?小数点?整数?
显然他可以把任何东西放在那里,它会编译并运行,但是你必须检查数据层中的类型并在类型不匹配时抛出异常(如果你不,您的数据库可能会)。
也许你可以改用泛型,比如
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
您还可以创建静态方法和 class 并让类型推断完成工作:
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);