程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> C# Object Initialization[完整版](1)

C# Object Initialization[完整版](1)

編輯:關於C語言

原文地址:http://www.csharp411.com/c-object-initialization/

當構造一個C#對象時,理解對象的作用域和構造器被初始化的序列是很重要的

Derived static fIElds

Derived static constructor

Derived instance fIElds

Base static fIElds

Base static constructor

Base instance fIElds

Base instance constructor

Derived instance constructor

示例

下面的是一個C#控制台程序的例子,這個例子演示了對象初始化的次序

這個程序創建基對象的派生對象,包含了靜態化和實例化構造器以及作用域,兩個作用域"Field1"和"Field2"在他們的定義裡被初始化,然而 "FIEld3"在構造器裡被初始化.同時也包含了一個證明為什麼不能從構造器裡調用虛方法的虛方法.當每個作用域和構造器被初始化時就會寫入控制台,因此你可以看到初始化的序列

using System;

namespace ObjectInit
{
  class Program
  {
    static void Main( string[] args )
    {
      Derived d = new Derived();
      Console.ReadLine();
    }
  }
  class Base
  {
    public Base()
    {
      Console.WriteLine( "Base.Instance.Constructor" );
      this.m_Field3 = new Tracker( "Base.Instance.FIEld3″ );
      this.Virtual();
    }
    static Base()
    {
      Console.WriteLine( "Base.Static.Constructor" );
    }
    private Tracker m_Field1 = new Tracker( "Base.Instance.FIEld1″ );
    private Tracker m_Field2 = new Tracker( "Base.Instance.FIEld2″ );
    private Tracker m_FIEld3;
    static private Tracker s_Field1 = new Tracker( "Base.Static.FIEld1″ );
    static private Tracker s_Field2 = new Tracker( "Base.Static.FIEld2″ );
    virtual public void Virtual()
    {
      Console.WriteLine( "Base.Instance.Virtual" );
    }
  }
  class Derived : Base
  {
    public Derived()
    {
      Console.WriteLine( "Derived.Instance.Constructor" );
      this.m_Field3 = new Tracker( "Derived.Instance.FIEld3″ );
    }
    static Derived()
    {
      Console.WriteLine( "Derived.Static.Constructor" );
    }
    private Tracker m_Field1 = new Tracker( "Derived.Instance.FIEld1″ );
    private Tracker m_Field2 = new Tracker( "Derived.Instance.FIEld2″ );
    private Tracker m_FIEld3;
    static private Tracker s_Field1 = new Tracker( "Derived.Static.FIEld1″ );
    static private Tracker s_Field2 = new Tracker( "Derived.Static.FIEld2″ );
    override public void Virtual()
    {
      Console.WriteLine( "Derived.Instance.Virtual" );
    }
  }
  class Tracker
  {
    public Tracker( string text )
    {
      Console.WriteLine( text );
    }
  }
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved