JAVA 与C#构造函数执行顺序的不同之处.

类别:Java 点击:0 评论:0 推荐:

JAVA: 先执行父类的构造函数,然后是引用对象的构造函数(必须有new声明实际类型),然后是自己的构造函数。
public class Test
{
  public static void main(String[] args)
  {
  Child child = new Child();
  }
}

class Parent
 {
   Parent()
   {
    System.out.println("to construct Parent.");
   }
  }

class Child extends Parent
 {
   Child()
   {
     System.out.println("to construct Child.");
   }
   Delegatee delegatee = new Delegatee();
 }


class Delegatee
{
  Delegatee()
   {
    System.out.println("to construct Delegatee.");
   }
}


结果是

而C#的构造函数执行顺序是:先引用对象,在父类,再子类.to construct Parent.
to construct Delegatee.
to construct Child.

using System;

namespace ConsoleApplication1
{
 public class Test
 {
  public static void Main(String[] args)
  {
   Child child = new Child();
  }
 }
 
 class Parent
 {
  public Parent()
  {
   Console.WriteLine("to construct parent");
  }
 }

 class Child : Parent
 {
  public Child()
  {
   Console.WriteLine("to construct Child.");
  }
  Delegatee delegatee = new Delegatee();
 }
 class Delegatee
 {
  public Delegatee()
  {
   Console.WriteLine("to construct Delegatee.");
  }
 }
}

结果是
to construct Delegatee.
to construct Child.
to construct Parent.


总结:
  被依赖的先构造,依赖于人的后构造。JAVA 是跨层依赖优先于同层依
赖构造,而C#是同层依赖优先于跨层依赖.

本文地址:http://com.8s8s.com/it/it11667.htm