为什么从来没有执行类节目的默认构造函数?从来没有、函数、类节目

2023-09-03 04:43:49 作者:starry(星空)

 命名TestApp
{
  类节目
  {
    公共项目()
    {
      变种breakpoint1 = 0;
    }

    静态无效的主要(字符串[]参数)
    {
      变种breakpoint2 = 0;
    }
  }
}
 

为什么的 断点1 的是永远不会打,但它击中的 断点2 的始终? ,是有办法进入前执行默认的构造函数主要()? 解决方案

没有程序的实例执行的方法类,这是可能的,因为它是一个静态方法。静态方法是可以无需构造/实例化从类的对象调用的方法。他们可以直接在类本身像这样调用:

  Program.Main(新的字符串[0]);

//执行有关程序类主静态方法
//空字符串数组作为参数
 

构造函数不是一个静态方法,打的断点,你需要实例化计划类,像这样的:

 静态无效的主要(字符串[]参数)
{
  变种breakpoint2 = 0;
  新计划(); // breakpoint1将被打
}
 
Visual C 程序设计 课程学习 5 第5章 C 面向对象程序设计基础

另外,您可以使构造静态,虽然无可否认它是不是真的那么从可测性的角度来看有用,也意味着你将有静态变量(即是全球可用的):

 静态程序(){
    变种breakpoint1 = 0;
    //断点将没有程序类的一个实例打
}
 

您可以阅读更多有关静态方法,这里。

namespace TestApp
{
  class Program
  {
    public Program()
    {
      var breakpoint1 = 0;
    }

    static void Main(string[] arguments)
    {
      var breakpoint2 = 0;
    }
  }
}

Why breakpoint 1 is never hit , but it hits breakpoint 2 always? And is there a way to execute the default constructor before entering Main() ?

解决方案

The Main method is executed without an instance of the Program class, which is possible because it is a static method. 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:

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.