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#是同层依赖优先于跨层依赖.