为什么 Main 方法是私有的?
新的控制台项目模板创建一个如下所示的 Main 方法:
class Program
{
static void Main(string[] args)
{
}
}
为什么 Main
方法和 Program
类都不需要是公共的?
New console project template creates a Main method like this:
class Program
{
static void Main(string[] args)
{
}
}
Why is it that neither the Main
method nor the Program
class need to be public?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
程序的入口点用
.entrypoint
IL 指令标记。方法或类是否是公共的并不重要,重要的是这个指令。The entry point of a program is marked with the
.entrypoint
IL directive. It does not matter if the method or the class is public or not, all that matters is this directive.Main
方法不需要由任何人调用。它实际上被标记为 EXE 本身执行的入口点,因此默认情况下没有外部调用者。
如果您想要,您可以通过标记
public
来打开它以供调用,例如,如果您要将控制台应用程序转换为API。The
Main
method shouldn't need to be called by anyone.It is actually marked as the entry point for execution in the EXE itself, and therefore has no outside callers by default.
If you WANT, you can open it up to be called by marking
public
, e.g. if you are turning a console app into an API.是的。您可以将
main()
方法标记为公共、私有或受保护。如果您想通过任何外部程序启动入口点,那么您可能需要将其公开,以便可以访问。如果您知道应用程序没有外部使用,则可以将其标记为私有,那么最好将其设为私有,这样外部应用程序就不会访问它。Yes. You can mark the
main()
method as public, private or protected. If you want to initiate the entry point by any external program then you might need to make it public so it is accessible. You can mark it as private if you know there is no external usage for the application then it is better to make it private so no external application access it.在这种情况下,公共或私有关键字没有什么区别,它完全取决于应用程序的用法和范围。在不同的场景中使用下面提到的关键字。
Public or Private keyword doesn't make a difference in this case, it completely depends on usage and scope of the application. Use below mentioned keywords in different scenarios.