[英]Why the default constructor of class Program is Never executed?
namespace TestApp
{
class Program
{
public Program()
{
var breakpoint1 = 0;
}
static void Main(string[] arguments)
{
var breakpoint2 = 0;
}
}
}
breakpoint 1
is never hit , but it hits breakpoint 2
always? 为什么breakpoint 1
永远不会被击中,但它始终击中breakpoint 2
? Main()
? 有没有办法在进入Main()
之前执行默认构造函数? The Main
method is executed without an instance of the Program
class, which is possible because it is a static method. Main
方法在没有Program
类实例的情况下执行,这是可能的,因为它是一个静态方法。 Static methods are methods that can be called without the need to construct/instantiate an object from the class. 静态方法是可以调用的方法,无需从类中构造/实例化对象。 They can be called directly on the Class itself like this: 它们可以直接在类本身上调用,如下所示:
Program.Main(new string[0]);
// executes the Main static method on Program class
// with empty string array as argument
The constructor is not a static method, to hit that breakpoint you need to instantiate the Program
class, like this: 构造函数不是一个静态方法,要点击你需要实例化Program
类的断点,如下所示:
static void Main(string[] arguments)
{
var breakpoint2 = 0;
new Program(); // breakpoint1 will be hit
}
Alternatively you can make the constructor static , though admittedly it is not really that useful from a testability standpoint and also implies that you're going to have static variables (that are globally available): 或者你可以使构造函数变为静态 ,但是从可测试性的角度来看它确实不是那么有用,并且暗示你将拥有静态变量(全局可用):
static Program() {
var breakpoint1 = 0;
// breakpoint will be hit without an instance of the Program class
}
You can read more about static methods here . 您可以在此处阅读有关静态方法的更多信
You are not instantiating the class. 你没有实例化这个类。 You are running a static Main()
method. 您正在运行static Main()
方法。 The run time will load the class and invoke the Main()
method .It doesn't need an instance of the class to invoke the Main()
method. 运行时将加载类并调用Main()
方法。它不需要类的实例来调用Main()
方法。 Constructor will run when you construct(instantiate) an object. 构造函数将在构造(实例化)对象时运行。
Your method is static: it will run without an instance of the class existing. 您的方法是静态的:它将在没有现有类的实例的情况下运行。 Your constructor is not: it is only executed when you create an instance of the class (that is, when you write new Program()
). 您的构造函数不是:它只在您创建类的实例时(即,当您编写new Program()
)执行。
In order to hit your breakpoint, most likely you want to change your constructor to be static Program()
instead. 为了达到您的断点,您很可能想要将构造函数更改为static Program()
。
The entry point to your program is equivalent to calling TestApp.Program.Main(args)
. 程序的入口点等同于调用TestApp.Program.Main(args)
。 The Program
class doesn't get instantiated. Program
类没有实例化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.