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

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.

主站蜘蛛池模板: 东丽区| 凤台县| 新邵县| 兴山县| 池州市| 巴林右旗| 饶阳县| 四平市| 射洪县| 建湖县| 芦山县| 教育| 扶绥县| 安新县| 延吉市| 乌什县| 新野县| 峨眉山市| 克山县| 射阳县| 当阳市| 蒲江县| 彭阳县| 浑源县| 秦皇岛市| 天津市| 那坡县| 洛南县| 皮山县| 灌云县| 南城县| 南康市| 封丘县| 商丘市| 肇庆市| 宝应县| 镇巴县| 鹤峰县| 阳高县| 宁远县| 逊克县|