使用 C# 扩展方法的 DTO 映射器

发布于 2024-10-19 23:01:20 字数 571 浏览 5 评论 0原文

将 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ら栖息 2024-10-26 23:01:20

撇开命名问题不谈,它没有什么根本性的错误,并且它在代码所在的位置方面提供了良好的 SOC,同时仍然提供了良好的 API。

也就是说,您应该考虑重命名您的函数。通常,函数是从目标(在本例中为您的 DTO)的角度命名的,而不是从结果的角度命名的。对于您的情况,我会将其命名为 ToAffiliateToBusinessObject(如果您希望在 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 or ToBusinessObject (if you want to have a consistent name across your DTO's) instead of FromDataTransferObject.

高速公鹿 2024-10-26 23:01:20

我不认为它有什么问题,它有助于可用性和可读性,并且对于手头的任务它也没有任何副作用。我自己也已经用过了。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文