Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我在某个网站上看到了这个例子:
public class infoData { public FridgeProduct fridgeProduct { get; private set; } }
如果冰箱产品字段被定义为公共并且可以通过定义从任何其他类访问,那么做私有设置器有什么意义?
私有 setter 的作用是只能从类内部写入属性,而不能从外部写入。
请注意,set 访问器上的访问规范(私有)会覆盖属性的访问规范(公共)。正如 Aluan Haddad 在评论中指出的那样,编译器强制单个访问器的可访问性不能比属性本身的可访问性限制更少。