Why is the class “Program” declared as static?

前端 未结 4 1087
后悔当初
后悔当初 2020-12-31 00:14

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

Which look

4条回答
  •  忘掉有多难
    2020-12-31 01:06

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

    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.

    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.

提交回复
热议问题