DTO。属性或字段? [英] DTOs. Properties or fields?

查看:154
本文介绍了DTO。属性或字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一些DTO类以跨WCF传输业务对象。

I need to create some DTO classes to transport our business objects across WCF.

由于这些只是没有功能的数据包,我有什么理由可以

Since these are just bags of data with no functionality, is there any reason I can't just use fields, or is there some good reason to expose them properly as properties?

//fields
[DataContract]
class CustomerDTO
{
    [DataMember] public int     Id;
    [DataMember] public string  Name;
}

//or properties?
[DataContract]
class CustomerDTO
{
    [DataMember] public int    Id               { get; set; }
    [DataMember] public string Name             { get; set; }
}


推荐答案

我主要赞成不可变DTO

I mostly favour immutable DTOs with read-only fields if I can get away with it:

public class CustomerDTO
{
    public CustomerDTO(int id, string name)
    {
        Id = id;
        Name = name;
    }

    public readonly int     Id;
    public readonly string  Name;

    // Override Equals and GetHashCode as well...
}

不可变的记录具有很多优点,例如结构相等性,这使自动测试断言的编写更加容易。它还无需编写和维护单独的测试数据生成器

There's lots of advantages to be had from immutable records, such as structural equality, which makes automated test assertions much simpler to write. It also dispenses with the need to write and maintain separate Test Data Builders.

但这取决于序列化程序。

It depends on the serializer, though. JSON.NET can handle immutable records, but many other serializers can't.

对于那些处理公共字段的人,我更喜欢字段而不是属性,这仅仅是因为它更诚实; 自动实现的读/写属性不提供封装

For those that handle public fields, I prefer fields over properties, simply because it's more honest; automatically implemented read/write properties provide no encapsulation.

某些序列化程序坚持使用公共属性,而不序列化字段。

Some serializers insist on public properties, and don't serialize fields. If that's the scenario, you have to go with that.

老实说,考虑到我对此有多大的考虑,这并不是让我彻夜难眠的东西,因为最终在边界处,应用程序不是面向对象的。因此,OOD规则实际上并不适用于DTO。

Honestly, considering how much thought I've put into this, it's not really something that keeps me awake at night, because ultimately, at the boundaries, applications aren't object-oriented. Thus, the rules of OOD don't really apply to DTOs anyway.

这篇关于DTO。属性或字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆