Affirmative 发表于 2021-5-17 14:52:33

C#,没有关联字段的属性,存储数据的问题

最近在看图解C#这本书,里面有一个章节:“6.18 访问器的访问修饰符”源代码:


因为我之前看的时候,说是属性没有内存空间,一般是关联字段进行存取。
但是看这个案例里面,Name这个属性直接就用了。我比较疑惑,有人可以解释下吗?

Affirmative 发表于 2021-5-17 15:20:44

往前翻书自己找到原理了,“自动实现属性”会隐式创建字段关联属性。

Automatically Implemented Properties—Auto-properties
Because properties are so often associated with backing fields, C# provides automatically implemented
properties, also called auto-implemented properties or, more commonly, just auto-properties, which allow
you to declare the property without declaring a backing field. The compiler creates a hidden backing field for
you and automatically hooks up the get and set accessors to it.
页: [1]
查看完整版本: C#,没有关联字段的属性,存储数据的问题