c#對象:先有雞還是先有蛋?

來源:互聯網
上載者:User
        碰巧看到呂震宇 兄的文章 C#設計模式(1) ,中提到 先有雞還是先有蛋 的代碼

using System;

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

class Base
{
   public int n = 9;
   public Derived d;
}

class Derived : Base
{
   public int m = 10;   
}

        “Derived繼承自Base,可以說沒有Base就沒有Derived,可Base裡面有一個成員是Derived類型。到底是先有雞還是先有蛋?這個程式可以正常編譯執行並列印結果10。”
     
         上面提到可以正常編譯並能列印結果,是沒錯,不過這不能說明先有雞還是先有蛋這個問題。先有雞還是先有蛋是說是雞先生蛋呢還是蛋生雞。在上面的代碼中Base類聲明有一個Derrived類,在Base執行個體化時,也就是“生”的時候並沒有把Derrived類也“生”出來,因此不能說明問題.
         Base類聲明有一個Derrived類,也就是Base類的執行個體有一個指向Derrived類的指標,這是個引用問題,而這個引用在Base類建立時為null。
         看下面的代碼:using System;

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

class Base
{
    public Base()
    {
        this.d = new Derived();
    }
    public int n = 9;
    public Derived d;
}

class Derived : Base
{
    public Derived() : base()
    {
    }
    public int m = 10;   
}

         在上面的代碼中Base類聲明有一個Derrived類,在Base執行個體化時,也就是“生”的時候把Derrived類也“生”出來,編譯通過,啟動並執行時候死迴圈!
        我不知道有什麼託管對象可以先在Object對象之前建立出來!
        Object對象作為所有其他對象的根對象,自然Object對象先建立出來,也就是說先有Object再有其他派生對象。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.