malaikuangren

What is the purpose or drive to build thing like (xxx),How can it achieve the original goal of design?
类成员初始化与构造函数执行的顺序 转自:http://www.cnblogs.com/anderslly/archive/2008/07/12/why-do-initializers-run-in-the-opposite-order-as-constructors.html

看看下面这段代码,你觉得它会输出什么呢?

    class Foo
    {
        public Foo(string s)
        {
            Console.WriteLine("Foo constructor: {0}", s);
        }
 
        public void Bar(){}
    }
 
    class Base
    {
        readonly Foo baseFoo = new Foo("Base initializer");
        public Base()
        {
            Console.WriteLine("Base constructor");
        }
    }
 
    class Derived : Base
    {
        readonly Foo derivedFoo = new Foo("Derived initializer.");
        public Derived()
        {
            Console.WriteLine("Derived constructor");
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            new Derived();
        }
    }
 
 
总结,类成员的初始化要先于类的构造器执行. 
基类的构造器先于子类的构造器的执行.

posted on 2008-07-12 21:14  malaikuangren  阅读(191)  评论(0编辑  收藏  举报