游泳

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

2019-09-13 19:20:57来源:励志吧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.");}}

结果是 to construct Parent. to construct Delegatee. to construct Child. 而C#的构造函数执行顺序是:先引用对象,在父类,再子类. 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#是同层依赖优先于跨层依赖.

查看本文来源

四个月宝宝怎么止咳
8个月宝宝发烧怎么办
小儿肠痉挛腹痛饮食注意什么
宝宝健脾吃什么好
分享到: