.net 中的受保护和私有声明
除了无法在类外部访问之外,受保护声明和私有声明之间是否有任何区别/优点?
Are there any difference/advantages between protected and private declaration apart from it not being accessible outside the class.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这些是辅助功能修饰符 - 这就是他们的重点。
These are accessibility modifiers - that's their point.
private
成员只能从类内部访问,protected
成员也可以由继承自它的类访问。private
members are only accessible from within the class,protected
members are also accessible by classes that inherit from it.从 MSDN 中查看此示例:
See the ax throws an error because you are attempts to access the property from the external of the class (calling the prop inside A from inside the class B).但 bx 是可以的,因为你是从 B 内部调用它的。有意义吗?
Check out this example from the MSDN:
See the a.x throws an error because you are trying to access the property from outside the class (calling the prop within A from inside the class B). But b.x is ok, because you are calling it from inside B. Make sense?
具有
protected
访问修饰符的成员可以在派生类中访问。而那些拥有private
访问修饰符的人只能在同一个类中访问。了解访问修饰符。
Members that have the
protected
access modifier are accessible in the derived classes. While those who have theprivate
access modifier are accessible only within the same class.Read about access modifiers.
struct
成员只能声明为public
、private
或internal
。class
成员可以声明为public
、protectedinternal
、protected
、internal
、或私有
。MSDN 上的访问修饰符
struct
members can only be declared aspublic
,private
orinternal
.class
members can be declared aspublic
,protected internal
,protected
,internal
, orprivate
.Access Modifiers on MSDN