官术网_书友最值得收藏!

Data structures should expose data and have no methods

Structures differ from classes in that they use value equality in place of reference equality. Other than that, there is not much difference between a struct and a class.

There is a debate as to whether a data structure should make the variables public or hide them behind get and set properties. It is purely down to you which you choose, but personally I always think it best to hide data even in structs and only provide access via properties and methods. There is one caveat in terms of having clean data structures that are safe, and that is that once created, structs should not allow themselves to be mutated by methods and get properties. The reason for this is that changes to temporary data structures will be discarded.

Let's now look at a simple data structure example.

An example of data structure

The following code is a simple data structure:

namespace CH3.Encapsulation
{
public struct Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }

public Person(int id, string firstName, string lastName)
{
Id = id;
FirstName = firstName;
LastName = lastName;
}
}
}

As you can see, the data structure is not that much different from a class in that it has a constructor and properties.

With this, we come to the end of the chapter and will now review what we've learned.

主站蜘蛛池模板: 红河县| 原阳县| 时尚| 新民市| 南江县| 澄迈县| 松江区| 龙岩市| 招远市| 民权县| 连江县| 柳林县| 临沧市| 龙岩市| 格尔木市| 华宁县| 泗水县| 敖汉旗| 蒙自县| 观塘区| 农安县| 平定县| 灵璧县| 苏尼特左旗| 汉阴县| 五原县| 兴隆县| 达日县| 萨嘎县| 个旧市| 丹巴县| 蓬安县| 雷波县| 怀宁县| 安宁市| 开平市| 玉屏| 札达县| 岗巴县| 施甸县| 保亭|