1.调试发现在创建Base 对象是,其中的Derived子对象并不会初始化,因为这只是个引用。如果这时直接使用这个子对象,会有异常抛出。当然本例中,因为创建了一个Derived对象,并赋给Base对象的子对象,所以不会有问题.

Derived继承自Base,可以说没有Base就没有Derived,可Base里面有一个成员是Derived类型。到底是先有鸡还是先有蛋?这个程序可以正常编译执行并打印结果10。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication10
{
    class Program
    {
        public static void Main()
        {
            Base b = new Base(); 
            Derived d = new Derived();
            b.d = d; 
            Console.WriteLine(b.d.m); 
        }
    }

    class Base 
    {
        public Base()
        {
        }

        public int n = 9;
        public Derived d;
    }

    class Derived : Base 
    {
        public Derived()
        {

        }
        public int m = 10
    }

}

 

 

2. 对此例子,做一点点小修改:将子对象初始话,你会发现Base和Derived的会循环调用,其实是进入了死循环。Base对象构造成功依赖其子对象先构建出来,而Derived对象构造函数会先调用其基类Base,所以,两者互相依赖,进入递归的死循环。

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication10
{
    class Program
    {
        public static void Main()
        {
            Base b = new Base(); 
            Derived d = new Derived();
            b.d = d; 
            Console.WriteLine(b.d.m); 
        }
    }

    class Base 
    {
        public Base()
        {
        }

        public int n = 9
        public Derived d = new Derived();
    }

    class Derived : Base 
    {
        public Derived()
        {

        }
        public int m = 10
    }

}

 

 

posted on 2012-05-23 16:13  higirle  阅读(196)  评论(0)    收藏  举报