为什么要选择“程序"类声明为静态? [英] Why is the class "Program" declared as static?

查看:86
本文介绍了为什么要选择“程序"类声明为静态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建 WinForm 应用程序时,会在 Program.cs 文件中获得一个自动生成的 Program 类模板.

When you create a WinForm App, you get an automatically generated template of Program class in the Program.cs file.

看起来像这样:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}

我的问题是,为什么 Program 类被声明为 static ?
如果删除 static 声明,它仍然可以正常工作.

My question is, why is the Program class declared as static?
If I remove the static declaration it still works fine.

该问题的原因是,我认为让 Program 从实现对

The reason for the question is that I thought it could be nice to have Program inherit from a base class that would implement handling of Application.ThreadException and AppDomain.CurrentDomain.UnhandledException instead of implementing it more or less the same for all of my projects.

推荐答案

它只是遵循设计准则,即仅包含 static 方法的类应标记为 static .可以在此处找到更多信息.

It just follows a design guideline, that classes that contain only static methods should be marked as static. More information can be found here.

使您的 Program 类不是静态的没有问题,唯一需要做的就是将 static Main 方法作为入口点,就像您已经知道的那样注意到了.您可以将实例方法添加到 Program 类中,对其进行实例化并用作其他任何类.但是,这不是一个明确的方法,因为它违反了单一责任原则. Program 的职责是为应用程序提供一个入口点,因此它不应做任何其他事情.对于此任务,它仅需要一个称为 Main static 方法.并且由于它仅包含 static 方法,因此应将其标记为 static 以符合 C#编码准则.

There is no problem in making your Program class not static, the only thing that is required is the static Main method as an entry point, as you've already noticed. You can add instance methods to the Program class, instantiate it and use as any other class. However this is not a clear way, as this violates the Single Responsibility Principle. Program's responsibility is to provide an entry point for the application, so it shouldn't do anything more. For this task it needs only one static method called Main. And as it contains only static methods, it should be marked as static to conform to C# coding guidelines.

通常,很容易知道一个类是 static ,因此乍一看,它只包含 static 方法.这是表达应该如何使用类的一种非常易读的方式.在此示例中,它不是很重要,因为没有人明确使用 Program ,但是出于严格的考虑,它应该是 static .

In general, it is convenient to know that a class is static, so you know at first glance that it contains only static methods. It is a very readable way of expressing how a class should be used. In this example it isn't very essential, as no one uses Program explicitly, however for the sake of strictness it should be static.

这篇关于为什么要选择“程序"类声明为静态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆