c# – 这些对象的实例化方式有何不同?

以下两种情况有什么区别:
class Data
{
    PersonDataContext persons = new PersonDataContext();
    public Data() {}
}

class Data
{
    PersonDataContext persons;
    public Data() 
    {
        persons = new PersonDataContext();
    }
}

我在asp.net中有同样的问题:

public partial class Data : System.Web.UI.Page
{
    PersonDataContext persons = new PersonDataContext();
    protected void Page_Load(object sender,EventArgs e)
    {
    }
}

public partial class Data : System.Web.UI.Page
{
    PersonDataContext persons;
    protected void Page_Load(object sender,EventArgs e)
    {
        persons = new PersonDataContext();
    }
}

解决方法

字段初始值设定项在构造函数调用之前运行.因此在案例1中,PersonDataContext的对象将在构造函数调用之前创建.
PersonDataContext persons = new PersonDataContext();

在第二种情况下,您的构造函数将首先执行,然后它将初始化该字段.

你可以做一个简单的测试

class PersonDataContext
{
    public PersonDataContext()
    {
        Console.WriteLine("In PersonDataContext Constructor");
    }
}
class Data
{
    PersonDataContext persons = new PersonDataContext();
    public Data() 
    {
        Console.WriteLine("In Data Contructor");
    }
}

class Data2
{
    PersonDataContext persons;
    public Data2() 
    {
        Console.WriteLine("In Data2 Constructor");
        persons = new PersonDataContext();
    }
}

然后在你的Main方法

static void Main(string[] args)
{

    Data d1 = new Data();
    Data2 d2 = new Data2();
    Console.Read();
}

产量

In PersonDataContext Constructor // Case 1

In Data Contructor //Case 1

In Data2 Constructor //Case 2

In PersonDataContext Constructor // Case 2

对于asp示例,在第一种情况下,Field在Page_Load事件之前初始化,在第二种情况下,Field在Page_Load事件中初始化

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...