为什么从来没有执行类节目的默认构造函数? [英] Why the default constructor of class Program is Never executed?

查看:128
本文介绍了为什么从来没有执行类节目的默认构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

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

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

 静态无效的主要(字符串[]参数)
{
  变种breakpoint2 = 0;
  新计划(); // breakpoint1将被打
}
 

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

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

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

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

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

  1. Why breakpoint 1 is never hit , but it hits breakpoint 2 always?
  2. 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.

这篇关于为什么从来没有执行类节目的默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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