不要这样做。有什么好处?
您的 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);