简体   繁体   English

什么时候应该宣布私人或公共课程?

[英]When should you declare a class private or public?

I usualy declare my classes public. 我通常会公开我的课程。 When does it make sense to declare a class private? 什么时候声明一个私有类是有意义的?

You can only declare a class as private when it's nested within another class. 当它嵌套在另一个类中时,您只能将类声明为私有。 Top-level classes can be made internal, however. 但是,顶级课程可以在内部完成。

You'd hide a class from the outside world when it's meant to be an implementation detail rather than providing an API everyone can use. 当它被认为是一个实现细节而不是提供每个人都可以使用的API时,你会隐藏一个来自外部世界的类。 The downside is that the outside world can't use that code directly even if it would be useful to them - the upside is that you can change the class however you like in the future without breaking the rest of the world, so long as your public API remains the same in both shape and behaviour. 缺点是外界不能直接使用该代码,即使它对他们有用 - 好处是你可以在不打破世界其他地方的情况下改变你喜欢的课程,只要你的公共API在形状和行为方面保持不变。

You can't declare class private unless it is nested class, if it is not it is internal. 除非它是嵌套类,否则不能声明类private,如果它不是内部的。 Why would you do this? 你为什么要这样做? Because this class is used internally in assembly and not needed by client. 因为此类在内部用于汇编而客户端不需要。

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

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