使用 C# 扩展方法的 DTO 映射器
将 DTO 映射器(大多数情况下是静态类)的成员定义为扩展方法是一个好主意吗?
然后
Affiliate bo = Mapper.FromDataTransferObject(dto);
我们可以写:
Affiliate bo = dto.FromDataTransferObject();
FromDataTransferObject 是下面定义的扩展方法:
public static Affiliate FromDataTransferObject(this AffiliateDto dto) {
if (dto == null) {
return null;
}
var bo = new Affiliate() {
Id = dto.Id,
AccountAlias = dto.AccountAlias,
Balance = dto.Balance
// ...
};
return bo;
}
Is it a good idea to define the members of a DTO mapper (which is most of the times a static class) as extension methods?
Then instead of writting:
Affiliate bo = Mapper.FromDataTransferObject(dto);
We may write:
Affiliate bo = dto.FromDataTransferObject();
FromDataTransferObject is an extension method defined below:
public static Affiliate FromDataTransferObject(this AffiliateDto dto) {
if (dto == null) {
return null;
}
var bo = new Affiliate() {
Id = dto.Id,
AccountAlias = dto.AccountAlias,
Balance = dto.Balance
// ...
};
return bo;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
撇开命名问题不谈,它没有什么根本性的错误,并且它在代码所在的位置方面提供了良好的 SOC,同时仍然提供了良好的 API。
也就是说,您应该考虑重命名您的函数。通常,函数是从目标(在本例中为您的 DTO)的角度命名的,而不是从结果的角度命名的。对于您的情况,我会将其命名为
ToAffiliate
或ToBusinessObject
(如果您希望在 DTO 中具有一致的名称),而不是FromDataTransferObject
。Naming issues aside, there's nothing fundamentally wrong with it, and it allows for good SOC in terms of where the code lies while still providing a good API.
That said, you should consider renaming your function. Typically, functions are named from the perspective of the target (in this case, your DTO), not from the perspective of the result. In your case, I would name it
ToAffiliate
orToBusinessObject
(if you want to have a consistent name across your DTO's) instead ofFromDataTransferObject
.我不认为它有什么问题,它有助于可用性和可读性,并且对于手头的任务它也没有任何副作用。我自己也已经用过了。
I don't see a problem with it, it helps useability and readability, and with the task at hand it doesn't have any side effects either. Used it myself as well already.