关于构造函数和主要方法执行的一点困惑

关于构造函数和主要方法执行的一点困惑

问题描述:

如果我们有一个构造函数和main()方法,首先会在执行表单/页面时调用它?

if we have a "constructor" and the "main()" method whichone will called first on the execution of the form/page?

主要是应用程序的静态入口点方法。应用程序启动时,首先调用Main。之后在正常情况下不再调用它。注意Main,不构造任何东西。如果你看一个普通的C#winform应用程序,它会说这样的话:



Main is a static entry point method for your application. When the application starts, Main is called first. After that it is not called anymore in normal circumstances. Note that Main, does not "construct" anything.! If you look at a normal C# winform application it will say something like this:

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

                  //new Form1 CONSTRUCTS the form.
		  Application.Run(new Form1());
		}
	}





使用 new keyword。

这是从模板=类构造对象的方法。这是通过实例化变量,事件,方法来完成的。



希望这会有所帮助。



The Constructor is called when you generate an object from a class with the new keyword.
It is the method that "constructs" the "object" from a template = the "class". This is done by instantiating the variables, event, methods, ...

Hope this helps.


不,它没有那样的工作! :笑:



每个项目/应用程序只有(或者应该)只有一个Main方法,它将在你的应用程序启动时被调用一次,之后只调用一次任何对象都是构造的。然后,如果将构建运行您的应用程序所需的对象,并在WinForms应用程序中包含该表单。通常情况下,你甚至不需要看它,更不用说改变它了! :$



每次创建类的实例时,都会立即调用类构造函数 - 因为它是实际构建对象实例并设置它的代码起始值。
No, it doesn''t work like that! :laugh:

There is (or should be) only one Main method per project / application, and it will be called once and only once when your application starts, before any objects are constructed. If will then construct the objects needed to run you application and that includes the form in a WinForms app. Normally, you don''t need to even look at it, much less change it! :D

Every time you create an instance of a class, the class constructor will be called immediately - as it is the code which actually builds the object instance and sets it starting values.