简体   繁体   English

为什么属性是公共的,而 setter 是私有的

[英]Why property is public and the setter is private

I saw this example on some website:我在某个网站上看到了这个例子:

public class infoData
{
    public FridgeProduct fridgeProduct { get; private set; }
}

What is the point to do private setter if fridgeProduct field is defined as public and can be accessed by definition from any other class?如果冰箱产品字段被定义为公共并且可以从任何其他 class 定义访问,那么做私有设置器有什么意义?

The private setter has the effect that the property can be written to only from within the class, not from outside.私有设置器的效果是,只能从 class 内部写入属性,而不能从外部写入。

Note that the access specification (private) on the set accessor overrides the access specification (public) of the property.请注意,set 访问器上的访问规范(私有)会覆盖属性的访问规范(公共)。 As Aluan Haddad noted in the comments, the compiler enforces that the accessibility of an individual accessor cannot be less restrictive than the accessibility of the property itself.正如 Aluan Haddad 在评论中指出的那样,编译器强制单个访问器的可访问性不能比属性本身的可访问性限制更少。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM